假设我有一个嵌套在字典键中的列表。所以像这样:

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)


这些是从combinations产生的对

[('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函数起作用,这应该会产生所需的行为。

07-24 09:44
查看更多