在下面的代码中,我试图用另一个名字打印每个名字一次:
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
如您所见,它工作正常,每个名字都是另一个名字的 friend ,但有一个重复,即 Nicole 和 Adam
已经提到为 Adam 和 Nicole
。我想要的是如何让代码不打印这种重复。
最佳答案
这是使用 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
关于python - 在 Python 中从列表中打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172827/