Python中从列表打印

3
在以下代码中,我试图将每个名称与另一个名称一起打印出来:
myList = ['John', 'Adam', 'Nicole', 'Tom']
for i in range(len(myList)-1):
    for j in range(len(myList)-1):
        if (myList[i] <> myList[j+1]):
            print myList[i] + ' and ' + myList[j+1] + ' are now friends'

我得到的结果是:
John and Adam are now friends
John and Nicole are now friends
John and Tom are now friends
Adam and Nicole are now friends
Adam and Tom are now friends
Nicole and Adam are now friends
Nicole and Tom are now friends

正如您所看到的,它可以正常工作,每个名称都是另一个名称的朋友,但存在重复,即Nicole和Adam已经被提及为Adam和Nicole。我想要的是如何使代码不打印这样的重复内容。


你可以跟踪已经提到的内容。 - Peter Wood
1
为了以后的参考,您需要将<>运算符更改为!= - Nayuki
3
你可以在外部循环之后从项目的下一个开始执行内部迭代,例如:for j in range(i + 1, len(myList)) - Peter Wood
1个回答

15

这是使用itertools.combinations的好机会:

In [9]: from itertools import combinations

In [10]: myList = ['John', 'Adam', 'Nicole', 'Tom']

In [11]: for n1, n2 in combinations(myList, 2):
   ....:     print "{} and {} are now friends".format(n1, n2)
   ....:
John and Adam are now friends
John and Nicole are now friends
John and Tom are now friends
Adam and Nicole are now friends
Adam and Tom are now friends
Nicole and Tom are now friends

哇,这是一个有趣的工具,我之前不知道它存在。 - JsingH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接