Reputation: 79
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)]
Upvotes: 3
Views: 867
Reputation: 34
Use loop and list comprehension
you can iterate over each tuple of list and then using list comprehension remove all the integers and add last element.
mylist = [('a',1,'b',2,'c',3), ('d',1,'e',2),('f',1,'g',2,'h',3,'i',4)]
newlist = []
#print(mylist)
for ele in mylist:
#print(ele)
list_1 = tuple(([ x for x in list(ele) if not str(x).isdigit() ] + [ele[-1]]))
newlist.append(list_1)
print("Final List :")
print(newlist)
after list comprehension add last element with index and convert that list to tuple and append it to your new list.
Upvotes: 0
Reputation: 36536
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)]
>>>
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)]
>>>
The inner list comprehension in the above expression can be replaced by a generator expression and the solution still works.
>>> 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)]
>>>
Upvotes: 0
Reputation: 29742
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)
.
Upvotes: 3
Reputation: 11550
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.
Upvotes: 0
Reputation: 19322
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,
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.
Upvotes: 0
Reputation: 1
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) #[]
Upvotes: 0