您如何排列(字符串)列表列表?你能用一套来做吗?

How do you permutate through a list of lists (of strings)? Can you do it with a set?

我想要

的输出

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

导致:

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

这可能吗?

如果我有一个更像这样的集合,它会更好用吗:

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

并使用拆分?

如果您正在寻找文字排列,请查看 itertools.permutations 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.combinations。

对于您的实际问题数据,如果任何内容的长度 > 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')]