![](/img/trans.png)
[英]How can I find all the possible combinations of a list of lists (in Python)?
[英]How can I list all possible combinations of a list together with their count in Python
大家好,这实际上是我在这里的第一个问题,所以如果我遗漏了一些信息,请告诉我。
我有一个包含数字的列表。 我想要所有可能的组合以及这些组合在我的列表中出现的频率。 这些组合应该遵循与 itertools 组合库相同的规则。
我的第一次尝试是一个循环,它将组合保存在字典中,但我只完成了 2 个数字的长度。 在那之后,我唯一的想法是一次又一次地循环,但我想这将花费很长时间,因为我的列表中将包含 600 多个元素。
我的第一次尝试是这样的:
def clean_dic(dic, sigma): #delete all canidates were frequency is smaller then sigma
dic = dict((k, v) for k, v in dic.items() if v >= sigma)
return dic
def create_canidate(seq,d_seq): #canidate creation with CDIST
for element in range(0,len(seq)):
s_check = set()
for skip in range (1,len(seq)-element):
number = tuple([seq[element], seq[element+skip]])
#get_freq
if number in d_seq and number not in s_check:
d_seq[number] += 1
elif number not in s_check and seq[element] in d_seq and seq[element+skip] in d_seq:
d_seq[number] = 1
s_check.add((seq[element], seq[element+skip]))
return d_seq
sequence = [1,2,3,4,1,2,1] #example sequence
#parameter
sigma = 2
#build dic
d_seq = dict()
d_seq = dict(Counter(sequence))
d_seq = clean_dic(d_seq, sigma)
d_seq = create_canidate(sequence, d_seq)
我已经知道创建所有组合的最佳方法可能是仅使用 set(combinations(sequence, loop through all length)) 但我无法弄清楚如何在不遍历所有内容且不保存任何内容的情况下获得计数......
所以问题是:完成任务的最佳方式是什么?它会是什么样子?
我将衷心感谢您的帮助:)
问候,
保罗
编辑:我想做的例子。 对于示例序列 [1,2,3,1,2] 我希望得到结果:1:2; 2:2; 3:1; 1,3:1; 1,1:1; 2,2:1; 2,3:1; 2,1:1; 3,1:1; 1,2,3:1; 1,2,1:1; 1,2,2:1; 1,3,1:1……等等。 请注意,必须保留订单。
我猜这是 output 和代码。
如果输入序列未排序,则(1, 1, 2)
与(1, 2, 1)
不同,这使得组合为奇数。
Output:
1 2
2 2
3 1
1,1 1
1,2 4
1,3 2
2,2 1
2,3 2
1,1,2 2
1,1,3 1
1,2,2 2
1,2,3 4
2,2,3 1
1,1,2,2 1
1,1,2,3 2
1,2,2,3 2
from collections import Counter
from itertools import combinations
seq = [1, 2, 3, 1, 2]
seq.sort() # so that the combination tuples are non-decreasing
counter = Counter()
for r in range(1, len(seq)):
counter.update(combinations(seq, r)) # let counter count the occurrences
# sort the result by combination length, combination tuple, and the count
results = sorted(counter.items(), key=lambda s: (len(s[0]), s[0], s[1]))
for components, count in results:
print(','.join(str(s) for s in components), count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.