假设我有一个嵌套在字典键中的列表。所以像这样:
d = {'people':['John', 'Carry', 'Joe', 'Greg', 'Carl', 'Gene']}
我想将列表中的人相互比较,以便我可以制作一个图表,连接以相同首字母开头的名称。
我想出了一个嵌套的 for 循环来尝试解决这个问题:
for subject in d.keys():
for word1 in d[people]:
for word2 in d[people]:
if word1[0] == word2[0]:
g.connectThem(word1,word2)
但是嵌套的 for 循环可能会变得多余,因为它会进行两次相同的比较。有什么办法可以让比较时不出现冗余吗?
最佳答案
您可以使用itertools.combinations
遍历对
for pair in itertools.combinations(d['people'], 2):
first, second = pair
if first[0] == second[0]:
g.connectThem(first, second)
这些是由组合
产生的对
[('John', 'Carry'), ('John', 'Joe'), ('John', 'Greg'), ('John', 'Carl'), ('John', 'Gene'),
('Carry', 'Joe'), ('Carry', 'Greg'), ('Carry', 'Carl'), ('Carry', 'Gene'),
('Joe', 'Greg'), ('Joe', 'Carl'), ('Joe', 'Gene'),
('Greg', 'Carl'), ('Greg', 'Gene'),
('Carl', 'Gene')]
请注意,您没有重复的问题(通过颠倒该对的顺序)。
假设您的 connectThem
函数有效,这应该会产生您想要的行为。
关于Python:比较不冗余的列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28129515/