I thought this would be fairly trivial but it’s turned out be more difficult than I’d anticipated.
I have a list of tuples:
tuples = [('apples', 2, 'apple'), ('oranges', 3, 'orange')]
I have list of lines containing a possible member of the tuple in the list of tuples:
list_of_lines = ['banana 1234', 'apple 5678', 'oranges 4321','apples 8765', 'orange 1111')]
For tuple[0] and tuple[2] in tuples, I need to match to the member in first position in list_of_lines and get that member’s value (in second position). The key thing is output these results on one line. For the first tuple in tuples, for example, the desired output would be:
'apples', 8765, 2, 'apple',5678
i.e. the original members of the tuple, now with values matched from list_of_lines.
If we try to do this with
for tup in tuples:
for line in list_of_lines:
if tuple[0] == line.split()[0]:
print tuple[0], line.split()[1]
if tuple[2] == line.split()[0]:
print tuple[2], line.split()[1]
then nothing is on one line and we get repeated matches.
Rather than scanning
list_of_linesevery time you need to locate an entry, it’s easier to pre-process the list into a dictionary:This prints out: