拆分词典列表的最佳方法?

2024-04-19 10:44:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经填充了如下所示的字典 (下面示例中的值只是显示我得到的列表):

{'name': 'name1'},
{'col': 'somename', 'col2': 12344},
{'col': 'somename', 'col2': 12344},
{'col': 'somename', 'col2': 12344},
{'name': 'name2'},
{'col': 'somename', 'col2': 12344},
{'name': 'name2'},
{'col': 'somename', 'col2': 12344},
{'col': 'somename', 'col2': 12344},
{'col': 'somename', 'col2': 12344},
{'col': 'somename', 'col2': 12344},
{'col': 'somename', 'col2': 12344},
{'col': 'somename', 'col2': 12344}

现在我想把它分成多个列表/目录。我想按'名字'键分开。我不知道如何用最好的方法做这件事。你知道吗

我想到的一个解决方案是遍历元素,当我发现“name”时,将其放入新的list/dict


Tags: 方法name目录元素示例列表字典col
1条回答
网友
1楼 · 发布于 2024-04-19 10:44:57

你可以在这里使用列表理解。 让输入列表为input_list

list1 = [x for x in input_list if 'name' in input_list]
list2 = [x for x in input_list if 'col' in input_list]

相关问题 更多 >