如何在多个 for 循环列表中找到最常见的整数

问题描述 投票:0回答:1

我正在研究反向凯撒密码,我在其中解密 26 种不同的组合以发现正确的换档键。

然后我将转换与常用词列表进行匹配,以找出匹配最多的键。我目前正在尝试返回最常见的匹配词转换。

matches = []
for words in shifted_combinations:
    if word in key_words:
        print(word, shift)

prints:
up 1
this 2
for 2
the 2
use 2
be 15
 

如果我然后尝试将班次附加到一个名为 matches 的新列表中,我会得到以下信息:

matches = []
for words in        shifted_combinations:
    matches.append(shift
        print(matches)

prints:
[1]
[2]
[2,2]
[2,2,2]
[2,2,2,2]
[15]

我将如何返回最常见的班次?这将是 2。我尝试了很多不同的方法,但似乎没有任何效果。理想情况下,我想先将所有数字都放入一个列表中。

任何帮助将不胜感激。

python list for-loop frequency caesar-cipher
1个回答
1
投票

我会用

collections.Counter

from collections import Counter

lists = [[1], [2], [2, 2], [2, 2, 2], [2, 2, 2, 2], [15]]

# for each list, count the items
# get the (first) most common
# retrieve the key
tops = [c[0][0] for x in lists if (c:=Counter(x).most_common(1))]
# [1, 2, 2, 2, 2, 15]

# get the most common top
Counter(tops).most_common(1)[0][0]
# 2

如果您有领带并想考虑它们,请使用自定义函数获取所有最常见的值:

from collections import Counter
from itertools import groupby

lists = [[1, 2], [2], [1, 1], [15]]

# Counter.most_common returns tuples of (key, count)
# in decreasing order of counts
# keep the keys of the first tuples that have the same count
def most_commons(lst):
    return [x[0] for x in
            next(groupby(Counter(lst).most_common(),
                         key=lambda x: x[1]),
                 (None, []))[1]]

tops = [k for x in lists for k in most_commons(x)]
# [1, 2, 2, 1, 15]

most_commons(tops)
# [1, 2]
© www.soinside.com 2019 - 2024. All rights reserved.