我有以下一系列词典:
dictionaty =[{'name': 'fire', 'command': '1;2;3;4'},
{'name': 'brain', 'command': '2;2;3;4'}, {'name': 'word', 'command': '1;3;4;5'},
{'name': 'cellphone', 'command': '6;1;3;4'}, {'name': 'ocean', 'command': '9;3;7;4'},
如何在“;”之后获取具有第二个和第三个值的命令的词典分别相等? 例如:'command':'1; 2; 3; 4'等于'command':'2; 2; 3; 4'
答案 0 :(得分:2)
您可以使用itertools.groupby
。您可以构造一个lambda
表达式,查找与'command'
键对应的值,然后在[1]
字符上找到分割的[2]
和';'
元素
d =[{'name': 'fire', 'command': '1;2;3;4'},
{'name': 'brain', 'command': '2;2;3;4'},
{'name': 'word', 'command': '1;3;4;5'},
{'name': 'cellphone', 'command': '6;1;3;4'},
{'name': 'ocean', 'command': '9;3;7;4'}]
import itertools
groups = itertools.groupby(d, lambda i: i['command'].split(';')[1:3])
for key, group in groups:
print(list(group))
输出
[{'name': 'fire', 'command': '1;2;3;4'}, {'name': 'brain', 'command': '2;2;3;4'}]
[{'name': 'word', 'command': '1;3;4;5'}]
[{'name': 'cellphone', 'command': '6;1;3;4'}]
[{'name': 'ocean', 'command': '9;3;7;4'}]
要查找包含多个成员的组,您还需要一个步骤:
for key, group in groups:
groupList = list(group)
if len(groupList) > 1:
print(groupList)
[{'command': '1;2;3;4', 'name': 'fire'}, {'command': '2;2;3;4', 'name': 'brain'}]
答案 1 :(得分:0)
您可以迭代这些项目,并为每个项目检查要关注的项目并比较'command'
的最后一部分:
dictionaty =[{'name': 'fire', 'command': '1;2;3;4'},
{'name': 'brain', 'command': '2;2;3;4'},
{'name': 'word', 'command': '1;3;4;5'},
{'name': 'cellphone', 'command': '6;1;3;4'},
{'name': 'ocean', 'command': '9;3;7;4'}]
for i, itm in enumerate(dictionaty):
itm_last_part = itm['command'].split(';')[2:]
for second in dictionaty[i+1:]:
second_last_part = second['command'].split(';')[2:]
if itm_last_part == second_last_part:
print itm, second, "are equal"
<强>输出强>
{'command': '1;2;3;4', 'name': 'fire'} {'command': '2;2;3;4', 'name': 'brain'} are equal
{'command': '1;2;3;4', 'name': 'fire'} {'command': '6;1;3;4', 'name': 'cellphone'} are equal
{'command': '2;2;3;4', 'name': 'brain'} {'command': '6;1;3;4', 'name': 'cellphone'} are equal