Getting a list of tuples that contain the same string

Viewed 53

days = ['Friday', 'Monday']

val1 = (('Friday, 23,4), ('Monday', 233,4), ('enjf', 33,2))

val2 = (('Friday, 3,4), ('Monday', 33,2))

So the upper one is just an example. What I want to do is that I want to get a total list of two tuples that contain the same string.

So for upper example, I would be expecting [('Friday, 23,4)('Friday, 3,4)] if I want tuples of 'Friday'. (This is just an example and I'm not trying to figure out the code for me to get the above result)

However, I wanna use this function in any case that has the same format as the above examples; multiple tuples in a list. Is there any way that I could use list comprehensions using filters to get such results?

2 Answers

You could make a function that finds all tuples by combining val1 and val2 and checking if their first value is in the desired set:

val1 = (('Friday', 23,4), ('Monday', 233,4), ('enjf', 33,2))
val2 = (('Friday', 3,4), ('Monday', 33,2))
all_vals = val1 + val2

def get_tuples(*keys):
    keys = set(keys)
    return [t for t in all_vals if t[0] in keys]

>>> get_tuples('Friday', 'Monday')
[('Friday', 23, 4), ('Monday', 233, 4), ('Friday', 3, 4), ('Monday', 33, 2)]
>>> get_tuples('Friday')
[('Friday', 23, 4), ('Friday', 3, 4)]

You can also use a defaultdict approach with argument unpacking via the star * operator:

from collections import defaultdict

days = ['Friday', 'Monday']

val1 = (('Friday', 23, 4), ('Monday', 233, 4), ('enjf', 33, 2))
val2 = (('Friday', 3, 4), ('Monday', 33, 2))

tuple_dict = defaultdict(list)
for day, *vals in val1 + val2:
    tuple_dict[day].append(vals)


def get_tuples(*keys):
    keys = set(keys)
    return [(k, *v) for k in keys
            for v in tuple_dict[k]]

Usage same as previous:

> get_tuples('Friday', 'Monday')
# [('Monday', 233, 4), ('Monday', 33, 2), ('Friday', 23, 4), ('Friday', 3, 4)]
> get_tuples('Friday')
# [('Friday', 23, 4), ('Friday', 3, 4)]

Related