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?
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]
[(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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With