我有一個不同長度的單詞串列。
我想在所有單詞的每個位置找到最頻繁出現的字符。這樣做并防止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))):
那么,如果兩個字符具有相同的頻率,第一個字符(基于字母表)被選為最常見的字符呢?
uj5u.com熱心網友回復:
嘗試:
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]
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/533654.html
上一篇:選擇排序代碼未輸出正確的值
