Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all integer from list in python

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)]
like image 569
pottttttossss Avatar asked Sep 16 '26 16:09

pottttttossss


1 Answers

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:

  1. 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.

  2. 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').

  3. (*filter, j): unpacks the result of 2 into a tuple whose last element is j.

    So it becomes ('a', 'b', 'c', 3).

like image 161
Chris Avatar answered Sep 19 '26 06:09

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!