简体   繁体   中英

Python comparing two list of tuple elements

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...

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]

@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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM