How do I remove all integers in my list except the last integer?
From
mylist = [('a',1,'b',2,'c',3), ('d',1,'e',2),('f',1,'g',2,'h',3,'i',4)]
To
[('a','b','c',3), ('d','e',2),('f','g','h','i',4)]
I tried doing below but nothing happens.
no_integers = [x for x in mylist if not isinstance(x, int)]
One way using filter with packing:
[(*filter(lambda x: isinstance(x, str), i), j) for *i, j in mylist]
Output:
[('a', 'b', 'c', 3), ('d', 'e', 2), ('f', 'g', 'h', 'i', 4)]
Explanation:
for *i, j in mylist: packs mylist's element (i.e. ('a',1,'b',2,'c',3), ...) into everything until last (*i) and the last (j).
So it will yield (('a',1,'b',2,'c'), 3) and so on.
filter(lambda x: isinstance(x, str), i): from i:('a',1,'b',2,'c'), filters out only str objects.
So ('a',1,'b',2,'c') becomes ('a','b','c').
(*filter, j): unpacks the result of 2 into a tuple whose last element is j.
So it becomes ('a', 'b', 'c', 3).
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