在2D列表python中查找最常见的数字组合

2024-09-29 17:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维列表。内部列表都由6个介于1和45之间的随机整数填充。我想找出在两到四个数字之间的每一个组合长度中,哪三个连续数字的组合最频繁出现,以及它们实际出现的频率。简而言之,我举了一个只有最常见的数字组合的例子,但我想你明白了。我想到的列表和代码:

intlst = [[29, 38, 17, 30, 33, 41], [12, 20, 30, 33, 29, 38], [12, 20, 30, 29, 38, 41], [17, 30, 33, 41, 33, 45], [27, 29, 17, 30, 33, 41]]

因此,长度为两个数的连续数的最常见组合是:29,38,出现三次

三个数字最常见的组合是:12、20、30,出现两次

最常见的四个数字组合是:17、30、33、41,出现三次

我想打印一个额外的文本结果,这样的功能将是伟大的。这应该是这样的:

def countcombinations(intlst, length):
    #do the math
    return result

    print("most occuring combinations with a length of two:",countcombinations(intlist, length),"\n most occuring combinations with a length of three:",countcombinations(intlist, length),"\n most occuring combinations with a length of four:",countcombinations(intlist, length))

因此,输出将如下所示:

most occuring combinations with a length of two: 29, 38 3x times
                                                 .., .. nx times
                                                 .., .. nx times


most occuring combinations with a length of three: 12, 20, 30 2x times
                                                   .., .., .. nx times
                                                   .., .., .. nx times


most occuring combinations with a length of four: 17, 30, 33, 41 3x times
                                                  .., .., .., .. nx times 
                                                  .., .., .., .. nx times

我用元组成功地得到了长度为2的结果,但我不知道如何用三个和四个数字的长组合来做同样的事情


Tags: ofmost列表with数字lengththreenx
1条回答
网友
1楼 · 发布于 2024-09-29 17:24:09

itertools.combines是执行此任务的最佳工具。见下文:

from itertools import combinations
from collections import Counter

def most_freq(l, n):
    temp=[]
    for i in l:
        temp.extend(tuple(k) for k in combinations(i, n))
    res = Counter(temp)
    return res

for i in range(2,5):
    print(most_freq(l, i))

n=2时的输出:

l=[[2, 13, 30, 33, 39, 41], [17, 20, 27, 33, 39, 38]]

>>>print(most_freq(l, i))

Counter({(33, 39): 2, (2, 13): 1, (2, 30): 1, (2, 33): 1, (2, 39): 1, (2, 41): 1, (13, 30): 1, (13, 33): 1, (13, 39): 1, (13, 41): 1, (30, 33): 1, (30, 39): 1, (30, 41): 1, (33, 41): 1, (39, 41): 1, (17, 20): 1, (17, 27): 1, (17, 33): 1, (17, 39): 1, (17, 38): 1, (20, 27): 1, (20, 33): 1, (20, 39): 1, (20, 38): 1, (27, 33): 1, (27, 39): 1, (27, 38): 1, (33, 38): 1, (39, 38): 1})
    

相关问题 更多 >

    热门问题