我正在計算是否eth出現btc在listy
searchterms = ['btc', 'eth']
listy = ['Hello, my name is btc', 'hello, my name is ETH,', 'i love eth', '#eth is great', 'barbaric tsar', 'nothing']
cnt = round((sum(len(re.findall('eth', x.lower())) for x in listy)/(len(listy)))*100)
print(f'{cnt}%')
解決方案只尋找eth. 如何查找多個搜索詞?
底線:我有一個搜索詞串列searchterms。我想看看有沒有出現在listy. 從那里,我可以執行串列中出現的這些術語的百分比。
uj5u.com熱心網友回復:
您需要使用管道“|” 在要搜索的值之間。在您的代碼中更改re.findall('eth', x.lower()為re.findall(r"(eth)|(btc)", x.lower()
listy = ['Hello, my name is btc', 'hello, my name is ETH,', 'i love eth', '#eth is great', 'barbaric tsar', 'nothing']
cnt = round((sum(len(re.findall(r"(eth)|(btc)", x.lower())) for x in listy)/(len(listy)))*100)
print(f'{cnt}%')
67%
uj5u.com熱心網友回復:
我想說的是,不要使問題復雜化并使用 re,而是使用簡單的經典串列理解。
listy = ['Hello, my name is btc', 'hello, my name is ETH,', 'i love eth', '#eth is great', 'barbaric tsar', 'nothing']
print(len([i for i in listy if 'btc' in i.lower() or 'eth' in i.lower()]) * 100 / len(listy))
它提高了代碼的可讀性和簡單性。
讓我知道它是否有幫助!
uj5u.com熱心網友回復:
更多的代碼提供了良好的可讀性。還添加了要搜索的其他單詞,只需將它們添加到串列中即可search_for。計算它使用默認字典。
listy = ['Hello, my name is btc', 'hello, my name is ETH,', 'i love eth', '#eth is great', 'barbaric tsar', 'nothing']
my_dict = defaultdict(int)
search_for = ['btc', 'eth']
for word in listy:
for sub in search_for:
if sub in word:
my_dict[sub] = 1
print(my_dict.items())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505447.html
標籤:Python python-3.x 列表
上一篇:來自兩個向量的不同數量元素的組合
