[英]List of lists: how to delete all lists that contain certain values?
There's a list of lists (or it could be tuple of tuples).有一个列表列表(或者它可能是元组的元组)。 For example:例如:
my_list = [
['A', 7462],
['B', 8361],
['C', 3713],
]
What would be the most efficient way to filter out all lists that have a value 'B'
in them, considering that the number (or other values) might change?考虑到数字(或其他值)可能会发生变化,过滤掉其中包含值'B'
的所有列表的最有效方法是什么?
The only way I came up with so far is using a for/in cycle (or rather a list comprehension) but it's very inefficient in this case, so I'd like to know if it's possible to avoid using a loop.到目前为止我想出的唯一方法是使用 for/in 循环(或者更确切地说是列表理解),但在这种情况下效率非常低,所以我想知道是否可以避免使用循环。
You can create a new list, filtering out the stuff you don't want.您可以创建一个新列表,过滤掉您不想要的内容。 In python this is usually done with a list comprehension:在 python 中,这通常是通过列表理解来完成的:
new_list = [sublist for sublist in my_list if sublist[0] != 'B']
You can use also use double-list comprehension.您也可以使用双列表理解。 [ [] ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.