Reputation: 951
I have to lists of tuples of the form (string, counter), like
tuples1 = [('A', 4), ('D', 8), ('L', 38)]
tuples2 = [('A', 24), ('B', 84), ('C', 321), ('D', 19) ...]
So the first list is a subset of the strings the second list has, but has a different number - the count of the string - for each string in the list. So I want all the strings that are in list 1, with both numbers.
I want to make it into one list of three terms, of the form ('string', tuples1[1], tuples2[1]). So for eg, with string 'D', it would be ('D', 8, 19).
I'm imagining I need to do something like for each string in tuples1, append an item to a list that has (tuples1[i][0], tuples1[i][1], tuples2[matchStringIndex][1]).
How do I program that?
Upvotes: 1
Views: 1306
Reputation: 239463
You can convert the list of tuple, which has to be searched, a dictionary and then get the corresponding count from that dictionary, like this
tuples1 = [('A', 4), ('D', 8), ('L', 38)]
tuples2 = [('A', 24), ('B', 84), ('C', 321), ('D', 19), ("L", 15)]
dict_tuples2 = dict(tuples2)
print [(char, count, dict_tuples2.get(char, 0)) for char, count in tuples1]
Output
[('A', 4, 24), ('D', 8, 19), ('L', 38, 15)]
Upvotes: 1