python-3.x 如何在多个字符串的每个位置上查找最频繁使用的字符

5jvtdoz2  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(110)

我有一个不同长度的单词表。
我想找到所有单词中出现频率最高的字符。有什么有效的方法可以做到这一点,并防止不同长度字符串中出现错误index out of range
例如:

alist = ['fowey', 'tynemouth', 'unfortunates', 'patroness', 'puttying', 'presumptuousness', 'lustrous', 'gloxinia']

在所有单词的每个位置上出现频率最高的字符(0 to len(max(alist, key=len)))等于:poternusakesness

for p in range (len(max(words, key=len))):

如果两个字符具有相同的频率,那么选择第一个字符(基于字母表)作为最频繁使用的字符怎么样?

cbjzeqam

cbjzeqam1#

请尝试:

from collections import Counter

alist = [
    "fowey",
    "tynemouth",
    "unfortunates",
    "patroness",
    "puttying",
    "presumptuousness",
    "lustrous",
    "gloxinia",
]

for i in (
    (w[idx] if idx < len(w) else None for w in alist)
    for idx in range(len(max(alist, key=len)))
):
    print(
        min(
            Counter(ch for ch in i if ch is not None).items(),
            key=lambda k: (-k[1], k[0]),
        )[0]
    )

印刷品:

p
u
t
e
r
n
u
s
a
o
e
s
n
e
s
s

编辑:使用collections.Counter

alist = [
    "fowey",
    "tynemouth",
    "unfortunates",
    "patroness",
    "puttying",
    "presumptuousness",
    "lustrous",
    "gloxinia",
]

for i in (
    (w[idx] if idx < len(w) else None for w in alist)
    for idx in range(len(max(alist, key=len)))
):
    cnt = {}
    for ch in i:
        if ch is not None:
            cnt[ch] = cnt.get(ch, 0) + 1

    print(
        min(
            cnt.items(),
            key=lambda k: (-k[1], k[0]),
        )[0]
    )

相关问题