繁体   English   中英

如何在多个字符串的每个位置找到最频繁出现的字符

[英]how to find the most frequent character in each postion of multiple strings

我有一个不同长度的单词列表。
我想在所有单词的每个 position 中找到出现频率最高的字符。 这样做并防止错误index out of range的有效方法是什么?
例如:

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

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

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

那么,如果两个字符具有相同的频率,第一个字符(基于字母表)被选为最常见的字符呢?

尝试:

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]
    )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM