David Williamson Williamson's Wonders 42.pdf
The following section of the article is a stub. Additional information.Q:
Unable to loop through list of tuples
This is not a duplicate as the question I'm asking has nothing to do with an OOP approach and I'm not using a list of tuples, I'm trying to loop through a list of tuples in a way to match one element with another element.
list_of_tuples = [[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'd'), (2, 'e'), (2, 'f')], [('1', 'a'), ('1', 'b')], [('1', 'a'), ('1', 'b'), ('2', 'd'), ('2', 'e'), ('2', 'f')], [('1', 'a'), ('1', 'b'), ('1', 'c'), ('2', 'd'), ('2', 'e'), ('2', 'f')], [('1', 'a'), ('1', 'b'), ('1', 'c'), ('2', 'd'), ('2', 'e'), ('2', 'f')]]
for x in list_of_tuples:
if (x[0],x[1]) in list_of_tuples:
print(x)
The first list [1, a] is repeating 3 times. So is the 2nd list [1, a] and the 3rd list [1, a]. They're repeating each time. How do I make it so that it only repeats each element once?
A:
In order to check for exact match, you need to make the tuple a key and the lists to compare are lists as well.
Your problem could be solved as:
for x in list_of_tuples:
if x[0] in list_of_tuples[x[0]]:
print(x)
As an alternate approach, you can use itertools.groupby as:
from itertools import groupby
for k,v in groupby(sorted(list_of_tuples),key=lambda x:x[0]):
print(list(v)) be359ba680
Related links:
Comments