组合时记录的Python频率

组合时记录的Python频率,python,python-3.x,tuples,permutation,frequency,Python,Python 3.x,Tuples,Permutation,Frequency,我已经开始在一个pet项目中使用python,因为在excel这样的程序中组织这些数据是不可能的。我希望你能给我一些指导,告诉我如何达到我想要的结果。请原谅我不懂python 我有下面的代码,我通过减少列表的数量和这些列表中的元素数量来简化这些代码,以使其更易于说明 import itertools from collections import Counter a = list(itertools.permutations([32,36,41],3)) b = list(itertools.

我已经开始在一个pet项目中使用python,因为在excel这样的程序中组织这些数据是不可能的。我希望你能给我一些指导,告诉我如何达到我想要的结果。请原谅我不懂python

我有下面的代码,我通过减少列表的数量和这些列表中的元素数量来简化这些代码,以使其更易于说明

import itertools
from collections import Counter

a = list(itertools.permutations([32,36,41],3))
b = list(itertools.permutations([36,32,41],3))
c = list(itertools.permutations([19,31,7],3))

fulllist = a+b+c

print(Counter(map(tuple, fulllist)))
结果如下:

Counter({(32, 36, 41): 2, (32, 41, 36): 2, (36, 32, 41): 2, (36, 41, 32): 2, (41, 32, 36): 2, (41, 36, 32): 2, (19, 31, 7): 1, (19, 7, 31): 1, (31, 19, 7): 1, (31, 7, 19): 1, (7, 19, 31): 1, (7, 31, 19): 1})
这已经很好了,但不是我所需要的。现在我有了intertools生成的每个列表组合的第一个计数,我不再关心所述列表中每个元素的顺序。因此,我想得到的最终结果是:

(32, 36, 41): 12 
(19, 31, 7): 6 
然后分类,就像我在上面写的一样。 我觉得我可能在兜圈子,也许有一个更简单的方法来获得我想要的结果。实际上,我的列表中有15个元素,其中大约有50个元素需要处理

我希望你能帮我做这件事。提前非常感谢。

如果您只需要对可能的排列进行计数,那么只需计算这些数字即可。该数字只是输入长度的阶乘:

import math

permutationcount = math.factorial(len(inputlist))
如果您创建的排列长度小于
len(inputlist)
(例如,20个中的3个),则公式为
n!/(n-k)!

当然,当
k
等于
n
时,则除以0!,这是1

您可以对输入列表进行排序,并将其转换为元组,以将键创建为映射:

from collections import Counter

def count_permutations(lists, k=None):
    counts = Counter()
    if k is None:
        k = len(lists[0])
    for l in lists:
        key = tuple(sorted(l))
        permutationcount = math.factorial(len(l)) // math.factorial(len(l) - k)
        counts[key] += permutationcount
    return counts
演示:


当然,您不需要在这里使用
计数器,但是如果您需要
。最常见的(
方法,并且不想查找如何按值对字典排序,那么使用
计数器可能会很方便。

如果您不计算排列(在这种情况下,请使用@Martin's answer),这只是用来创建一个示例列表,只是排序以明确顺序并不重要:

>>>print(Counter(tuple(sorted(x)) for x in fulllist))
Counter({(32, 36, 41): 12, (7, 19, 31): 6})

那么真正的最终结果是计数?为什么不直接计算这些计数,而不是生成所有这些组合?
counts={}
,然后
key=tuple(sorted(inputlist))
count=math.factorial(len(inputlist))
counts[key]=counts.get(key,0)+count
,其中'inputlist是这三个输入之一。根本不需要生成任何排列。旁注:不需要
映射(tuple,…)
,因为所有排列都已经是tuple了。您真的应该使用
itertools.chain()
组合置换迭代器。对于完整的50个列表结果,您是否生成长度为3或15的置换?这是如何解决OPs问题的?你在哪里把数字整理成排序集?@MartijnPieters。你说得对。我没有对元组排序。
>>> count_permutations(([32,36,41], [36,32,41], [19,31,7]), k=3)
Counter({(32, 36, 41): 12, (7, 19, 31): 6})
>>>print(Counter(tuple(sorted(x)) for x in fulllist))
Counter({(32, 36, 41): 12, (7, 19, 31): 6})
c = Counter(map(tuple, fulllist))
l = [ {tuple(sorted(i[0])):i[1]} for i in c.items()]  

for e in l:
    print(e)  

{(32, 36, 41): 2}
{(32, 36, 41): 2}
{(32, 36, 41): 2}
{(32, 36, 41): 2}
{(32, 36, 41): 2}
{(32, 36, 41): 2}
{(7, 19, 31): 1}
{(7, 19, 31): 1}
{(7, 19, 31): 1}
{(7, 19, 31): 1}
{(7, 19, 31): 1}
{(7, 19, 31): 1}