我正在尋找幾個小時的答案,但不幸的是在任何地方都找不到適合我的問題的答案。
假設我有一個看起來像這樣的字串 -
str_int = "I'm 35, and I have 2 kids ages 10 and 12"
我想從這些 str 中匯出最常見長度的所有數字。所以滿足結果將是:
[35,10,12]
請注意,數字 2 不在陣列中,因為我只想要長度最頻繁的數字。
我也想將此應用于浮點數。所以如果我有以下字串:
str_float = "I'm 35.055, and I have 2.100 kids ages 10.0 and 12.505"
預期結果將是:
[35.055, 12.505]
請注意,這兩個數字是 5 位數字,另外兩個數字分別是 4 位和 3 位數字,所以我想要最常見的數字長度數字,即具有 5 位數字的數字。
希望有道理,謝謝!
uj5u.com熱心網友回復:
您可以使用 提取數字,使用re.findall找到最常見的長度collections.Counter,然后列出具有此長度的數字:
import re
from collections import Counter
def most_freq(s):
lst = [(x, len(x) - ('.' in x)) for x in re.findall(r"\d (?:\.\d )?", s)]
frequent_length, _ = Counter(x[1] for x in lst).most_common(1)[0]
return [x[0] for x in lst if x[1] == frequent_length]
str_int = "I'm 35, and I have 2 kids ages 10 and 12"
str_float = "I'm 35.055, and I have 2.100 kids ages 10.0 and 12.505"
str_another = "0.017 0.019 3 1 0.020 2 0.024 3 0.032 0.0157"
print(most_freq(str_int)) # ['35', '10', '12']
print(most_freq(str_float)) # ['35.055', '12.505']
print(most_freq(str_another)) # ['0.017', '0.019', '0.020', '0.024', '0.032']
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/348231.html
