Python deletes element samples that meet certain conditions in the list.
This example describes how to delete elements that meet certain conditions in the list in Python. We will share this with you for your reference. The details are as follows:
Delete elements that meet certain conditions from the list.
For example, delete an element with a length of 0 in the list, or delete an element with a multiple of 2 and 3 in the list.
Those who have done advanced language programming will take it for granted that "this is very simple" and can be implemented in the following ways:
for i in listObj: if(...): listObj.remove(i)
Let's look at the following small example and result:
a = [1, 2, 3, 12, 12, 5, 6, 8, 9]for i in a: if i % 2 == 0 and i % 3 == 0: a.remove(i)print(a)
Running result:
E:\Program\Python>d.py[1, 2, 3, 12, 5, 8, 9]
Have you seen it? 12. It was not deleted !!! (This is a very error-prone place for Python list operations)
There are still many alternatives to achieve the expected goals, such:
a = [1, 2, 3, 12, 12, 5, 6, 8, 9]b = a[:]for i in a: if i % 2 == 0 and i % 3 == 0: b.remove(i)a = bprint(a)
Running result:
E:\Program\Python>d.py[1, 2, 3, 5, 8, 9]
Let's see, now we have achieved our expected goal. From the above code, we can easily find that we have constructed List B, copied all the elements in list a, traversed a to delete the elements in List B, and finally pointed a to B.
I also found another method, which I think is quite good --List Derivation
a = ['what', '', '', 'some', '', 'time']a = [i for i in a if len(i) > 0]print(a)b = [1, 2, 3, 12, 12, 5, 6, 8, 9]b = [i for i in b if not(i % 3 == 0 and i % 2 == 0)]print(b)
Running result:
E:\Program\Python>d.py['what', 'some', 'time'][1, 2, 3, 5, 8, 9]
In comparison, which of the following statements do you think is better ?? In terms of performance, the efficiency may not be very good, but in terms of concise writing, I prefer the latter!
For more Python-related content, refer to this topic: Python list) operation Skills summary, Python coding skills summary, Python data structure and algorithm tutorial, Python function usage skills summary, Python string operation skills summary, Python basic and advanced tutorial and Python file and directory operation tips
I hope this article will help you with Python programming.