Home > Enterprise >  Remove all integer from list in python
Remove all integer from list in python

Time:12-01

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)]

CodePudding user response:

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)]

CodePudding user response:

A nested list comprehension would do the job:

r = [('a','b','c',3), ('d','e',2),('f','g','h','i',4)]

[tuple([y for y in x if not isinstance(x, 'int')]) for x in r]

OUTPUT

[('a', 'b', 'c'), ('d', 'e'), ('f', 'g', 'h', 'i')]

CodePudding user response:

clear(), pop(), and remove() are methods of list. You can also remove elements from a list with del statements.,In Python, use list methods clear(), pop(), and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.,It is also possible to delete all items by specifying the entire range.,See the following example.

l=list(range(10)) print(l) #[0,1,2,3,4,5,6,7,8,9] l.clear() print(l) #[]

CodePudding user response:

Using only list comprehensions

there will always be the last integer on each tuple. There's no scenario where the end will be a string.

Keeping your above comment in mind,

  1. Your approach is almost right, except for the fact that your list is actually a list of tuples. This means you need a nested loop to iterate through the items inside the sublist.
  2. Knowing that the last element is an integer (last integer) that has to be kept, you can simply just do the above iteration on n-1 items of each sublist, and then append the last item regardless of the condition.

Check comments for an explanation of each component.

[tuple([item for item in sublist if not isinstance(item, int)] [sublist[-1]]) for sublist in l]

#|___________________________________________________________| |____________| 
#                            |                                       |
#  Same as your method, iterating on n-1 items for each tuple        |
#                                                               append last item
#|____________________________________________________________________________________________|
#                                           |
#   Iterate over the list and then iterate over each sublist (tuples) with condition
[('a', 'b', 'c', 3), ('d', 'e', 2), ('f', 'g', 'h', 'i', 4)]

So, simply use your method for iterating inside the sublist, while having a separate for loop to iterate through the sublists.

CodePudding user response:

You can use listcomp and unpacking like this.

[
    (*[c for c in subl if not isinstance(c, int)], last)
    for *subl, last in mylist
]

Out: [('a', 'b', 'c', 3), ('d', 'e', 2), ('f', 'g', 'h', 'i', 4)]

PS: Updated after this answer. Thanks Chris.

CodePudding user response:

Assumptions

If we can assume the int we want to keep will always be the last element in each tuple, this is very easy. We'll just filter everything except the last element and reconstruct a tuple using the result.

>>> [tuple(list(filter(lambda x: not isinstance(x, int), l[:-1]))   [l[-1]]) for l in mylist]
[('a', 'b', 'c', 3), ('d', 'e', 2), ('f', 'g', 'h', 'i', 4)]
>>>

Less assumption

But what if, as originally specified in your question, we just want to get rid of all ints... except the last one and we don't know what order or positions things will occur in?

First a function that might provide handy:

>>> def partition(pred, lst):
...     t, f = [], []
...     for x in lst:
...         (t if pred(x) else f).append(x)
...     return (t, f)
...
>>>

We can easily partition your data into ints and not ints with this:

>>> partition(lambda x: isinstance(x, int), mylist[0])
([1, 2, 3], ['a', 'b', 'c'])
>>> [partition(lambda x: isinstance(x, int), lst) for lst in mylist]
[([1, 2, 3], ['a', 'b', 'c']), ([1, 2], ['d', 'e']), ([1, 2, 3, 4], ['f', 'g', 'h', 'i'])]
>>>

Then we'd just need to discard all but the last of the ints, but how would we know where to put them back together? Well, if we were to enumerate them first...

>>> [partition(lambda x: isinstance(x[1], int), enumerate(lst)) for lst in mylist]
[([(1, 1), (3, 2), (5, 3)], [(0, 'a'), (2, 'b'), (4, 'c')]), ([(1, 1), (3, 2)], [(0, 'd'), (2, 'e')]), ([(1, 1), (3, 2), (5, 3), (7, 4)], [(0, 'f'), (2, 'g'), (4, 'h'), (6, 'i')])]
>>>

Now we just discard all but the last int, and add it back into the list of not ints to create a single list.

>>> [(i[-1], ni) for i, ni in [partition(lambda x: isinstance(x[1], int), enumerate(lst)) for lst in mylist]]
[((5, 3), [(0, 'a'), (2, 'b'), (4, 'c')]), ((3, 2), [(0, 'd'), (2, 'e')]), ((7, 4), [(0, 'f'), (2, 'g'), (4, 'h'), (6, 'i')])]
>>> [ni   [i[-1]] for i, ni in [partition(lambda x: isinstance(x[1], int), enumerate(lst)) for lst in mylist]]
[[(0, 'a'), (2, 'b'), (4, 'c'), (5, 3)], [(0, 'd'), (2, 'e'), (3, 2)], [(0, 'f'), (2, 'g'), (4, 'h'), (6, 'i'), (7, 4)]]
>>>

If we sort by the indexes we added on with enumerate:

>>> [sorted(ni   [i[-1]], key=lambda x: x[0]) for i, ni in [partition(lambda x: isinstance(x[1], int), enumerate(lst)) for lst in mylist]]
[[(0, 'a'), (2, 'b'), (4, 'c'), (5, 3)], [(0, 'd'), (2, 'e'), (3, 2)], [(0, 'f'), (2, 'g'), (4, 'h'), (6, 'i'), (7, 4)]]
>>>

Now we need to discard the indexes and convert back to tuples.

>>> [tuple(map(lambda x: x[1], sorted(ni   [i[-1]], key=lambda x: x[0]))) for i, ni in [partition(lambda x: isinstance(x[1], int), enumerate(lst)) for lst in mylist]]
[('a', 'b', 'c', 3), ('d', 'e', 2), ('f', 'g', 'h', 'i', 4)]
>>>

Now, even if we change up the input data, we keep only the last int, and where it originally was:

>>> mylist = [('a',1,'b',2,'c',3,'d',6,'e','f'), ('d',1,'e',2),('f',1,'g',2,'h',3,'i',4)]
>>> [tuple(map(lambda x: x[1], sorted(ni   [i[-1]], key=lambda x: x[0]))) for i, ni in [partition(lambda x: isinstance(x[1], int), enumerate(lst)) for lst in mylist]]
[('a', 'b', 'c', 'd', 6, 'e', 'f'), ('d', 'e', 2), ('f', 'g', 'h', 'i', 4)]
>>>
  • Related