[英]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...]
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.