Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehension filtering with tuples (containing integers as strings)

I am trying to filter the following list: tuple = [('7:29', 0.5), ('99:2', 0.35714285714285715), ('10:2', 0.35714285714285715)] using list comprehension, filtering based on the first elements from the tuples between the character ':'. For example: filter = [7, 99], thus the result would be: new_tuple = [('7:29', 0.5), ('99:2', 0.35714285714285715)].

I tried the following solution:

filter_string = [str(item) for item in filter]
tuple_filtered = [(x,y) for (x,y) in tuples if x in filter]

but it returns an empty list and I don't have any idea how to fix it. Can somebody please help me?

like image 686
working-yoghurt-1995 Avatar asked Apr 23 '26 09:04

working-yoghurt-1995


2 Answers

First when you apply this line:

filter_string = [str(item) for item in filter]

You apply str() function over a tuple object - making all the tuple in to a string. for example - str(('99:2', 0.35714285714285715)) --> '(\\'99:2\\', 0.35714285714285715)' Which in my sense just make it harder to parse.

Second, tuple is a saved name in python - do not use it and run it over! it can cause very annoying bugs later on.

Finally, you can look at a tuple as a fixed size array which is indexed, which mean you can address the first element (that you want to filter by)

Something like that:

my_tuples = [('7:29', 0.5), ('99:2', 0.35714285714285715), ('10:2', 0.35714285714285715)]
my_filter = [7, 99]
filtered_list =  [t for t in my_tuples if int(t[0].split(':')[0]) 
                  in my_filter]
like image 141
Green Avatar answered Apr 25 '26 23:04

Green


[(x,y) for (x,y) in tuples if  str(x.split(":")[0]) in filter_string ]

Equivalently:

op = []
for (x,y) in tuples :
    if str(x.split(":")[0]) in filter_string:
        op.append((x,y))
like image 38
abhinonymous Avatar answered Apr 25 '26 23:04

abhinonymous