1

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?

2
  • you should really use collections.Counter to do your counting, or at the very least use a dict-based data structure rather than a list of tuples. Commented Jan 19, 2014 at 20:19
  • I am using collections.Counter, counted = collections.Counter(lister) sortedCounter = counted.most_common() tuplesIT = sorted(sortedCounter) #tuples form ('word','instances') of all the words in the tweets - "tuples In Tweets" Commented Jan 19, 2014 at 20:21

1 Answer 1

1

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

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.