Reputation: 3760
I have to compare two list of tuple elements and combine some math calculation of the elements themselves.
More precisely, I have the following lists, every tuple of the list_1
represents a single character and it's frequence into a text ex. ("a" : "10)
, every tuple of the list_2
represents a bigram of characters and their frequence into the same text ex. ("a", "b" , "2")
:
list_1=[("a","10"), ("b","5"), ("c","3"),("d","1")]
list_2= [("a", "b", "4"), ("b","c","1")]
I need to iterate over the two lists and in the case there is a match between the characters of list_2
and the caracters of the list_1
, my goal is to make the following analisys:
x= ("a","10")*("b","5")/("a","b","4")= 10*5/4
I hope i was clear in the explanation of the problem...
Upvotes: 2
Views: 291
Reputation: 44465
@sparkandshine's is the better solution, but for clarity, here is a verbose approach for those new to Python and unfamiliar with comprehensions:
def compute(bigrams, table):
"""Yield a resultant operation for each bigram."""
for bigram in bigrams:
# Get values and convert strings
x = int(table[bigram[0]])
y = int(table[bigram[1]])
z = int(bigram[2])
operation = (x * y) / z
yield operation
list(compute(list_2, dict(list_1)))
# [12.5, 15.0]
Upvotes: 1
Reputation: 18007
Try this,
list_1=[("a","10"), ("b","5"), ("c","3"),("d","1")]
list_2= [("a", "b", "4"), ("b","c","1")]
# Convert list_1 into a dict
d = {t[0]:int(t[1]) for t in list_1}
result = [d.get(t[0], 0)*d.get(t[1], 0)*1.0/int(t[2]) for t in list_2]
print(result)
#[12.5, 15.0]
Upvotes: 2