+ 1
Remove problem
How to remove more than one item or different items at one time? For example: nums=[1,2,3,3,3,4,5,4] Can I remove all 3 or 2 and 4 in one line? And how to remove the second 4?
7 Respostas
+ 3
# if you are looking for a one liner try
nums=[1,2,3,3,3,4,5,4]
# filter out all duplicates from a list
print(list(set(nums)))
# or if you just want it as a set just go
print(set(nums))
# remove specific numbers from a list
# an example of removing all 3's and 4's
print([x for x in nums if x not in [3,4]])
# or to alter by index position use slicing notation
# remove the last position from the list
print(nums[:-1])
+ 1
you have to iterate the list and remove the nodes you don't need with a condition, you can use a while or you can do it with a recursive method. Hope it helps :)
+ 1
@Ladislav Milunovic
What do you mean??
+ 1
@Luciano Pumeda Ale
Could you write me an example?
Thank you so much: )
+ 1
That way you just fill your [set()] list, you have to add the condition to erase the numbers you don't want
0
mySet = set()
for e in nums:
mySet.add(e)
0
I mean to create set. It is type that doesn't accept duplicates. if you have a list just iterate it and add items to set. or make set imideatelly if you dont want duplicates