简体   繁体   English

如何从列表中删除一些对?

[英]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.

相关问题 如何根据列表格式的值从字典中删除键值对并与其他列表值有一些交集 - how to remove key value pairs from a dictionary based on values which are in list format and having some intersection with other list values 如何从满足 Python 中某些条件的列表中获取所有对 - How to get all pairs from a list that fulfil some condition in Python 如何反转 python 中的某些特定列表对 - how to reverse some specific pairs of a list in python 如何从列表中删除一些元素取决于一些标准 - how to remove some elements from list depends upon some criteria 如何根据 Pandas 中的某些条件创建包含列中的值对的元组列表? - How to create a list of tuples containing pairs of values from a column based on some conditions in Pandas? 如何从字符串中删除相同的数字对? - How to remove pairs of identical digits from a string? 如何从列表中创建单词对列表 - how to create a list of word pairs from a list 如何从键与列表中的项目匹配的字典中删除键值对? - How to remove key-value pairs from a dictionary where the key matches an item in a list? 如何从列表中查找和删除具有给定总字母数的字符串对 - How to find and remove pairs of strings with a given total letters count from a list 如何从列表中的某些字符串中删除特定字符串? - How do I remove a specific string from some strings in a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM