简体   繁体   中英

Printing from list in Python

In the following code, I am trying to print each name with another name once:

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'

The result that I got is:

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

As you can see, it works fine and each name is a friend with another name but there is a repetition which is Nicole and Adam which already mentioned as Adam and Nicole . What I want is how can I make the code doesn't print such repetition.

This is a good opportunity to use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM