如何在列表的列表(字符串)中进行排列?你能用一套来做吗?



我想输出

nums = (("2q","3q","4q","3q"),("1q"), ("1q","2q"))

导致:

pairs = (("2q", "3q"), ("2q", "1q"),("1q","2q")).......

这可能吗?

如果我有一个像

这样的集合会更好吗?nums = (("2q,3q,4q,3q"),("1q"), ("1q,2q"))

并使用分隔符?

如果您正在寻找文字排列,请查看itertools。排列https://docs.python.org/3/library/itertools.html

的例子:https://www.geeksforgeeks.org/python-itertools-permutations/

from itertools import permutations  
a = 'string value here.' # list or string value.
a = ['2q', '3q', '4q'] #... Add other items here.
p = permutations(a,2)   #for pairs of len 2
# Print the obtained permutations  
for j in list(p):  
print(j)  
#For multiple length clusters..
for c in range(min_cluster_len, max_cluster_len): 
for j in list(permutations(a, c)):
print(j)
#Output: 
('2q', '3q')
('2q', '4q')
('2q', '5q')
('3q', '2q')
('3q', '4q')
('3q', '5q')
('4q', '2q')
('4q', '3q')
('4q', '5q')
('5q', '2q')
('5q', '3q')
('5q', '4q')
('2q', '3q', '4q')
('2q', '3q', '5q')
('2q', '4q', '3q')
... 

如果顺序无关紧要,即(2q, 3q) == (3q, 2q),则使用itertools.combination

对于实际的问题数据,如果有长度>x,我不确定你是怎么把这些分组的,所以不完全确定。也可以使用正则表达式,但不理想。

我想你的nums有一个错别字…如果您希望它们都是元组,则("1q")必须有一个逗号,如("1q",):

nums = (("2q","3q","4q","3q"),("1q",), ("1q","2q"))

如果输入是元组的元组(或列表的列表,等等),下面给出了假设可以选择两次值的所有对:

import itertools
from more_itertools import distinct_permutations
out = list(distinct_permutations(itertools.chain.from_iterable(nums), r=2))
print(out)
[('1q', '1q'), ('1q', '2q'), ('1q', '3q'), ('1q', '4q'), ('2q', '1q'), ('2q', '2q'), ('2q', '3q'), ('2q', '4q'), ('3q', '1q'), ('3q', '2q'), ('3q', '3q'), ('3q', '4q'), ('4q', '1q'), ('4q', '2q'), ('4q', '3q')]

如果您不希望在对中出现重复,您可以在运行它之前使用set来消除它们:

out_no_duplicates = list(distinct_permutations(set(itertools.chain.from_iterable(nums)), r=2))
print(out_no_duplicates)
[('1q', '2q'), ('1q', '3q'), ('1q', '4q'), ('2q', '1q'), ('2q', '3q'), ('2q', '4q'), ('3q', '1q'), ('3q', '2q'), ('3q', '4q'), ('4q', '1q'), ('4q', '2q'), ('4q', '3q')]

最新更新