Python:遍历列表并返回列表中所有字符串的元组排列?
Python: Iterating through a list and returning a tuple permutation for all strings in the list?
我有一个元素列表:list = ['A','B',C']。如何遍历此列表和 return 以下内容:[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])
我有一个元素列表:list = ['A','B',C']。如何遍历此列表和 return 以下内容:[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])