2024-04-20 02:18:48 发布
网友
我想要一份
nums = (("2q","3q","4q","3q"),("1q"), ("1q","2q"))
导致:
pairs = (("2q", "3q"), ("2q", "1q"),("1q","2q")).......
可能吗
如果我有一套更像:
nums = (("2q,3q,4q,3q"),("1q"), ("1q,2q"))
然后用劈叉
我想你的nums有一个打字错误。。。如果希望它们都是元组,("1q")必须有一个逗号,如("1q",):
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消除它们:
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')]
如果要查找文字置换,请查看itertools.permutationshttps://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.compositions
对于您的实际问题数据,如果任何内容的长度大于或等于;x、 我不确定你是如何将这些进行分组的,所以不完全确定。也可以使用正则表达式,但并不理想
我想你的
nums
有一个打字错误。。。如果希望它们都是元组,("1q")
必须有一个逗号,如("1q",)
:如果输入是元组的元组(或列表的列表等),则假设可以选择两次值,则以下给出所有对:
如果不希望成对出现重复项,可以在运行之前使用
set
消除它们:如果要查找文字置换,请查看itertools.permutationshttps://docs.python.org/3/library/itertools.html
示例来自: https://www.geeksforgeeks.org/python-itertools-permutations/
如果顺序不重要,即(2q,3q)=(3q,2q),则使用itertools.compositions
对于您的实际问题数据,如果任何内容的长度大于或等于;x、 我不确定你是如何将这些进行分组的,所以不完全确定。也可以使用正则表达式,但并不理想
相关问题 更多 >
编程相关推荐