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]
According to these lists i need to match 'duran' with 1 'sang' with 1 'wild' with 4 'boys' with 2 etc.
according to this formula : math.log(4/(number matched with the string goes here), 10)
(ex: math.log(4/1, 10) equals 0.602)
how do i repeat this code unlike this:
[math.log(4/1, 10), math.log(4/1, 10), math.log(4/4, 10)]
so it will repeat for every word in output 1
and final output will be this for example :
[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]
if you need further clarification please tell me
CodePudding user response:
This is a simple list comprehension.
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])
Output:
[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]
List (and dict) comprehensions are awesome :-)