[英]how can i find the most frequent character for each position in a file full of strings and return the highest frequent characters for each position
[英]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.