我在如何在遍历列表时删除元素中读到这个: Remove elements as you traverse a list in Python
以此为例:
>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
但是如果我想删除属于字符串一部分的元素,我该怎么做呢? 即,如果我只输入“een”(只是颜色中“绿色”字符串元素的一部分?
最佳答案
使用 list comprehension而不是使用 filter()
:
>>> colors = ['red', 'green', 'blue', 'purple']
>>> [color for color in colors if 'een' not in color]
['red', 'blue', 'purple']
或者,如果您想继续使用 filter()
:
>>> filter(lambda color: 'een' not in color, colors)
['red', 'blue', 'purple']
关于python - 遍历列表时如何删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18040251/