laszlopanaflex
laszlopanaflex

Reputation: 1916

filtering a list of lists containing tuples

i have the following example:

tuples = [[('2018','Q1','Dept1'),('2018','Q2','Dept2')],[('2018','Q1','Dept1'),('2018','Q1','Dept2')],[('2018','Q2','Dept1'),('2018','Q2','Dept2')]]

so each item in tuples is a list with 2 elements, each of which is a tuple of 3 elements.

i want to produce a final list, newlist, which is filtered according to the first 2 values of each tuple in each list being equivalent

so, so in this example, i would expect newlist to look like:

[[('2018', 'Q1', 'Dept1'), ('2018', 'Q1', 'Dept2')],
 [('2018', 'Q2', 'Dept1'), ('2018', 'Q2', 'Dept2')]]

this is a simplified example, while real size of tuples could be much larger

Upvotes: 1

Views: 395

Answers (2)

U13-Forward
U13-Forward

Reputation: 71580

Try the below, iterating trough tuples, then check if first two elements of first element of i is the same as the second element's:

>>> [i for i in tuples if i[0][:2]==i[1][:2]]
[[('2018', 'Q1', 'Dept1'), ('2018', 'Q1', 'Dept2')], [('2018', 'Q2', 'Dept1'), ('2018', 'Q2', 'Dept2')]]
>>> 

Or course you can also use filter:

>>> list(filter(lambda i: i[0][:2]==i[1][:2]],tuples))
[[('2018', 'Q1', 'Dept1'), ('2018', 'Q1', 'Dept2')], [('2018', 'Q2', 'Dept1'), ('2018', 'Q2', 'Dept2')]]
>>> 

Upvotes: 2

emschorsch
emschorsch

Reputation: 1669

I'd first make a dictionary based on the first two elements:

entries = {}
for tuple in tuples:
    key = tuple[:2]
    entries[key] = entries.get(key, []) + [tuple[2]]

Then you can reconstruct your newlist

newlist = []
for entry, values in entries.items():
    sublist = []
    for val in values:
        sublist.append(entries + (val,))
    newlist.append(sublist)

Upvotes: 0

Related Questions