如何将带冒号标识的字符串列表转换为分组字典?
如何将特定格式的Python列表转换为字典?
给定以下格式的Python列表:
inp = ["arg1:", "list", "of", "args", "arg2:", "other", "list"]
需要生成对应的字典:
out = {"arg1": ["list", "of", "args"], "arg2": ["other", "list"]}
需求逻辑
- 遍历输入列表,找到以冒号结尾的元素(如
arg1:) - 去除冒号后作为字典的键,对应值设为空列表
- 继续遍历,将后续元素添加至该键的列表中,直到遇到下一个带冒号的元素
- 重复上述步骤直至处理完所有元素
其他示例
# 示例1 inp = ["test:", "one", "help:", "two", "three", "four"] out = {"test": ["one"], "help": ["two", "three", "four"]} # 示例2 inp = ["one:", "list", "two:", "list", "list", "three:", "list", "list", "list"] out = {"one": ["list"], "two": ["list", "list"], "three": ["list", "list", "list"]}
解决方案
方法一:基础遍历法
这是最直观的实现方式,通过跟踪当前键来收集对应元素:
def list_to_dict(inp): result = {} current_key = None for item in inp: if item.endswith(':'): # 提取键并初始化空列表 current_key = item[:-1] result[current_key] = [] else: # 将元素添加到当前键的列表中 if current_key is not None: result[current_key].append(item) return result # 测试验证 inp = ["arg1:", "list", "of", "args", "arg2:", "other", "list"] print(list_to_dict(inp)) # 输出: {'arg1': ['list', 'of', 'args'], 'arg2': ['other', 'list']}
方法二:迭代器优化法
利用迭代器的特性,可以避免重复遍历,逻辑更紧凑:
def list_to_dict(inp): result = {} it = iter(inp) for item in it: if item.endswith(':'): key = item[:-1] result[key] = [] # 收集后续元素,直到遇到下一个带冒号的键 for sub_item in it: if sub_item.endswith(':'): # 将下一个键放回迭代器,交给外层循环处理 it = iter([sub_item]) + it break result[key].append(sub_item) return result # 测试验证 inp = ["test:", "one", "help:", "two", "three", "four"] print(list_to_dict(inp)) # 输出: {'test': ['one'], 'help': ['two', 'three', 'four']}
内容的提问来源于stack exchange,提问作者turbonerd
相关产品推荐
相关产品推荐

