繁体   English   中英

Python:遍历列表并返回列表中所有字符串的元组排列?

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

我有一个元素列表:list = ['A','B',C']。 如何遍历此列表并返回以下内容:[AB, AC, BC]?

注意:我只想要唯一的对,而不是 [AA, BB, CC...] 或 [AB, BA, BC, CB...]

你需要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')

你可以这样做

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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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