ls = [[1], [1, 2], [1, 2, 3], [], [2], [2, 3], [], [], [3]]
Is there any python list method that will enable me to remove all the similar items at once. For example, I have a 2d list 'ls' which has three empty list items []. I want to remove all the empty list items at once. I know it can be done with 'remove' and 'loop.' But is there any method to do the operation at once? To be simple: I want all the '[]' to be deleted. And thus the answer would be like this. [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
There is no remove_all
method or anything like that, but the best ways to accomplish this are with a list comprehension or filter
.
Assuming that ls
only contains other lists you can write the following to remove all occurrences of the empty list []
:
ls = [[1], [1, 2], [1, 2, 3], [], [2], [2, 3], [], [], [3]]
ls = [x for x in ls if x]
# now ls = [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
ls = [[1], [1, 2], [1, 2, 3], [], [2], [2, 3], [], [], [3]]
ls = list(filter(None, ls))
# now ls = [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
If you wanted to remove all occurrences of a given element elem
(that is not the empty list) you can modify the above code as follows:
ls = [x for x in ls if x != elem]
##### or #####
ls = list(filter(lambda x: x != elem, ls))
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.)
https://docs.python.org/3.8/library/stdtypes.html#set-types-set-frozenset
You can do something like this. But it is specific to this case:
ls = [[1], [1, 2], [1, 2, 3], [], [2], [2, 3], [], [], [3]]
[l for l in ls if len(l)!=0]
You can use filter
here to remove all the []
lists and maintaining the order.
list(filter(None,ls))
# [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
List comprehension of the above would be
[lst for lst in ls if lst]
# [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
You can try the followings approaches:
1)
l = [x for x in ls if x != []]
or
l = [x for x in ls if x]
2)
l = filter(None, ls)
you could use collections.Counter
with the built-in function filter
:
from collections import Counter
count = Counter(map(str, ls))
ls = list(filter(lambda x: count[str(x)] == 1, ls))
ls
output:
[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.