+ 19
Does Python List Comprehension with 2 if conditions work properly?
I have used an existing code (for loop) and tried to do the same task with list comprehension and 2 conditional expressions, but the result is not as it should be. The conditional statement is exactly the same In both code samples. The code should pick doublicates from a source list and put them to separate list. Here are both codes: https://code.sololearn.com/cmMwjVDBbfcO/?ref=app
4 odpowiedzi
+ 4
oh, you simply need to append the numbers to duplst or else your “i not in duplst” will look at an empty list.
lst = [1,2, 4, 3, 2, 7, 90, 1]
duplst = []
[duplst.append(i) for i in lst if lst.count(i) > 1 and i not in duplst]
print(duplst)
+ 9
Diego, Tibor Santa, Choe thank you very much for your support! It was a small issue in my code which I did not recognize and you gave me real good and helpful solutions. I appreciate your help very much - Thanks!
+ 6
The problem with v4 is that "duplist" is not updated after each iteration, so "i not in duplist" checks for "i" in an empty list.
If you don't care about order you can do
print([i for i in set(lst) if lst.count(i) > 1]) # [1, 2]
If you do care about order you can do
print([i for i in sorted(set(lst), key=lambda n: lst.index(n)) if lst.count(i) > 1]) # [1, 2]
+ 6
Also this can work
In the second condition you check if the element occurs in the original list up to the current index
duplst = [v for k, v in enumerate(lst) if lst.count(v) > 1 and v not in lst[:k]]