在以下代码中,我试图将每个名称与另一个名称一起打印出来:
我得到的结果是:
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
。我想要的是如何使代码不打印这样的重复内容。
<>
运算符更改为!=
。 - Nayukifor j in range(i + 1, len(myList))
。 - Peter Wood