[英]How to remove some pairs from list?
I have a list like [[2,3], [7,6], [12,567],[18,4]].我有一个像 [[2,3], [7,6], [12,567],[18,4]] 的列表。 I need to remove a pair, when second element of pair is bigger than 5.
当对的第二个元素大于 5 时,我需要删除一对。
for x in table:
if x[1] > 5:
del x
I tried this way, but list index out of range .我试过这种方式,但list index out of range 。 How to do it correctly?
如何正确地做到这一点?
I would do it like this:我会这样做:
table = [[2,3], [7,6], [12,567],[18,4]]
table = [x for x in table if not x[1] > 5]
You may want to learn more about the concept of list comprehensions.您可能想了解更多关于列表推导式的概念。 I find this article gives a good introduction:
我发现这篇文章给出了一个很好的介绍:
https://www.digitalocean.com/community/tutorials/understanding-list-comprehensions-in-python-3 https://www.digitalocean.com/community/tutorials/understanding-list-comprehensions-in-python-3
Python中有一个filter
函数:
new_table = list(filter(lambda x: x[1] <= 5, table))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.