+ 3
[solved](python)Shortcut to express list1-list2 ?
I have 2 lists: list1 = [1,2,3,4] list2 = [3,4] If I want to prevent the numbers in list2 to be shown in list1, is there a shortcut for that? Or I have to write long code like below: list1 = [1, 2, 3, 4] list2 = [3, 4] temp_list = [] i = 0 while i < len(list1): if list1[i] not in list2: temp_list.append(list1[i]) i += 1 list1 = temp_list print(list1)
19 ответов
+ 16
[i for i in list1 if i not in list2]
https://code.sololearn.com/cbn7mwGiujgk/?ref=app
+ 10
[edited]
sorry, the lists sequence in the lambda was wrong. here the correct version:
list1 = [1, 2, 3, 4]
list2 = [3, 4]
print(list(filter(lambda x:x not in list2, list1)))
Lea ,
just for the sake of completeness: using filter with a lambda function can also do this job:
list1 = [1, 2, 3, 4]
list2 = [3, 4]
print(list(filter(lambda x:x not in list1, list2))) # not correct!
+ 7
print(list(set(list1) - set(list2)))
+ 5
the modules name to import is 'collections' not 'collection'
^
+ 4
Oma Falk I just tried! You are right! Thank you for pointing it out!
https://code.sololearn.com/cGX90sT9QgaI/?ref=app
+ 4
Prabhas Koya
Thank you for providing more solutions!
By the way,
Is “collection” a moduler i need to add to my library before I run the code?
+ 3
Simba This is so cool! It means I can apply all the mathematical operations for sets on lists!
+ 3
I wonder why lists don’t have mathematical opertations like sets.
Sets and lists, it seems both of them are for holding data, but their methods are so different…..
+ 3
for i in list2:
try:
list1.remove(i)
except:
pass
'''
Looping only through list2, I think this is efficient. Hatsy Rei is looping through extra items in list1 . IF YOU KNOW YOUR LIST2 CONTAINS ELEMENTS WHICH ARE DEFINITELY IN LIST1 , THEN SIMPLY
for i in list2: list1.remove(i)
'''
making more faster
import collections
list1 = collections.deque([1,1,2,3])
list2 = [3,4]
for i in list2:
try:
list1.remove(i)
except:
pass
+ 2
☺️
+ 2
Hi, Lothar I ran you code and get the result below:
[]
+ 2
Yes , you need to import before running your code.
+ 1
Here it goes
list1 = [1, 1, 2, 3, 4]; list2 = [3, 4]
list0 = list(set(list1 + list2)); print(list0)
+ 1
Lothar yeah that was a typo thanks for correcting
0
I need your help guys to improve my code