Compare one-dimensional lists in Python and delete the same elements

Asked 2 years ago, Updated 2 years ago, 19 views

I would like to exclude elements in li2 from li.
I try to say li=[4], but li=[2,4].
Thank you for your cooperation.

 li = [1,2,3,4]
li2 = [1,2,3]

for i in li:
    if i in li2:
        li.remove(i)

print(li)

python

2022-09-30 19:05

2 Answers

For only looks at the i-th of the target list in order and doesn't seem to know if the target list is rewritten.
Like li[:], it works as you think it would to have another object with the same content.
http://docs.python.jp/2.7/reference/compound_stmts.html#the-for-statement

Notes

There is a subtle problem with changing the sequence during a loop (this happens in a changeable sequence, that is, in a list).An internal counter is used to track which element is used next, which is added for each iteration.When this counter reaches the length of the sequence, the loop terminates.This means that if you remove the current (or previous) element from the sequence in the suite, the next element will be skipped (because the index of the next element will be the index of the element that you have already dealt with):Similarly, if you insert an element before the current element in the sequence in the suite, the current element will be treated again in the loop.These specifications are troubling bugs.You can avoid this by making temporary copies using slices equivalent to the entire sequence.

 for x in a [:]:
    if x <0: a.remove(x)


2022-09-30 19:05

Creating a new list object is code-simplified.

list (filter(lambdax:x not in li2, li))
[4]

Or

list(x for x in li if x not in li2)

Also, for details, it is theoretically faster to put li2 together.

 li = [1,2,3,4]
s = {1,2,3}

li = list (filter(lambdax:x not in, li))

print(li)
[4]

If li or li2 gets bigger, consider using the set.


2022-09-30 19:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.