简体   繁体   中英

Python: Iterating through a list and returning a tuple permutation for all strings in the list?

I have a list of elements: list = ['A','B',C']. How do I iterate through this list and return the following: [AB, AC, BC]?

note: I only want unique pairs, not [AA, BB, CC...] or [AB, BA, BC, CB...]

You need itertools.combinations :

In [1]: from itertools import combinations

In [2]: for c in combinations(['A', 'B', 'C'], 2):
   ...:     print(c)
   ...: 
('A', 'B')
('A', 'C')
('B', 'C')

you can do it this way

lst = ['A','B','C']
result=[]
for i in range(len(lst)):
    for j in range(i+1,len(lst)):
        result.append(lst[i]+lst[j])

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