import math
text = ["duran duran sang wild boys in 1984", "wild boys don't reman forever wild", "who brought wild flowers", "it was john krakauer who wrote in to the wild"]
print(text)
def get_unique_words(a):
visited = set()
uniq = []
for b in a.split():
if b not in visited:
uniq.append(b)
visited.add(b)
return uniq
def get_unique_words_from_list_of_strings(str_list):
return get_unique_words(' '.join(str_list))
words_in_order = get_unique_words_from_list_of_strings(text)
def countInListOfLists(l, x):
counts = [s.count(x) for s in l]
return sum([1 for c in counts if c > 0])
def dfcounter():
return [countInListOfLists(text, word) for word in words_in_order]
print(dfcounter())
output1 is ['duran', 'sang', 'wild', 'boys', 'in', '1984', "don't", 'remain', 'forever', 'who', 'brought', 'flowers', 'it', 'was', 'john', 'krakauer', 'wrote', 'to', 'the']
output2 is [1, 1, 4, 2, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
根據這些串列,我需要將 'duran' 與 1 'sang' 與 1 'wild' 與 4 'boys' 與 2 等匹配。
根據這個公式:(math.log(4/(number matched with the string goes here), 10)例如:math.log(4/1, 10) 等于 0.602)
與此不同,我如何重復此代碼:
[math.log(4/1, 10), math.log(4/1, 10), math.log(4/4, 10)]
所以它會為輸出 1 中的每個單詞重復
最終輸出將是這樣的,例如:
[0.602, 0.602, 0.0, 0.301, 0.301, 0.602, 0.602, 0.602, 0.602, 0.301, 0.602, 0.602, 0.602, 0.602, 0.602, 0.602, 0.602, 0.602, 0.602]
如果您需要進一步說明,請告訴我
uj5u.com熱心網友回復:
這是一個簡單的串列理解。
import math
mylist = [1, 1, 4, 2, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print([math.log(4.0/x, 10) for x in mylist])
輸出:
[0.6020599913279623, 0.6020599913279623, 0.0, 0.30102999566398114, 0.30102999566398114, 0.6020599913279623, 0.6020599913279623, 0.6020599913279623, 0.6020599913279623, 0.30102999566398114, 0.6020599913279623, 0.6020599913279623, 0.6020599913279623, 0.6020599913279623, 0.6020599913279623, 0.6020599913279623, 0.6020599913279623, 0.6020599913279623, 0.6020599913279623]
串列(和字典)理解很棒:-)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/382605.html
