从Python列表打印

Nas*_*ser 3 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'
Run Code Online (Sandbox Code Playgroud)

我得到的结果是:

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
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,它工作正常,每个名字都是另一个名字的朋友,但有一个重复Nicole and Adam,已经提到过Adam and Nicole.我想要的是如何使代码不打印这样的重复.

Ran*_*ndy 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
Run Code Online (Sandbox Code Playgroud)