2

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

1
  • 1
    well, since you seem to know exactly what you want to do I suggest you write some code? Commented Dec 2, 2016 at 10:41

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks so much sparkandshine! Your answer works good! I have only another little question. What I have to do if I want a result like this: ab=12.5 , bc=15.0 ?
Try this, for t, value in zip(list_2, result): print(''.join([t[0], t[1], '=', str(value)]))
Hello sparkandshine! Now I need to solve the same problem but I have three characters in evry item of the list_2? For ex. list_2[("a", "b", "c", 3)]. How can I change cope with this?
@CosimoCuriale, do something like result = [d[t[0]]*d[t[1]]*d[t[2]]/int(t[3]) for t in list_2].
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.