从Python列表打印

时间:2015-10-16 14:23:42

标签: python list

在下面的代码中,我尝试使用其他名称打印每个名称一次:

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 and Adam,已经提到Adam and Nicole。我想要的是如何让代码不打印这样的重复。

1 个答案:

答案 0 :(得分: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