python - 在 Python 中从列表中打印

标签 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

如您所见,它工作正常,每个名字都是另一个名字的 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/

相关文章:

python - 在 Python 中使用 Google map API

python - 如何使用python将列表列表拆分为列表中的每个列表到一个字典

c# - 列表排序的烦恼

Python:类型错误:文本必须是 unicode 或字节

python - 将两个列表,一个作为键,一个作为值,合并到 Python 中的字典中

list - ViM:如何将输入对话框中的字符串放入列表中

python - 重命名写入的 CSV 文件 Spark 抛出错误 "Path must be absolute"- Azure Data Lake

python - 如何从包含 munch 的字典中编写 YAML,而不使用 "!munch.Munch"?

python - 装饰器调用实例方法

Python:如何统计实例变量的访问次数