在Python中从列表打印
在以下代码中,我尝试用另一个名称打印每个名称一次:在Python中从列表打印,python,list,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 friend
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'
如您所见,它工作正常,每个名字都是另一个名字的朋友,但有一个重复,即
Nicole和Adam
,已经提到了Adam和Nicole
。我想要的是如何使代码不打印这种重复。这是一个使用itertools的好机会。组合:
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
您可以跟踪已经提到的内容。为了将来参考,您需要将
运算符更改为=代码>。在外部迭代之后,您可以从项目1执行内部迭代,例如:对于范围内的j(i+1,len(myList))
Wow这是一个有趣的工具,我不知道。
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