简体   繁体   English

查找列表中其字段与值匹配的所有元素

[英]Find all the elements of a list whose field match with a value

If I have a list like this:如果我有这样的列表:

[element(name='A', value=0), element(name='B', value=1)]

I would like to find all the element of the list whose value field is equal to 0:我想找到值字段等于0的列表的所有元素:

element[:].value == 0

Which would the shortest way?哪条路最短?

elements = [element(name='A', value=0), element(name='B', value=1)]
matches = [element for element in elements if element.value == 0]

To get the names from all the matches:要从所有匹配项中获取名称:

names = [element.name for element in matches]
print(names)

A list comprehension should do the trick列表理解应该可以解决问题

not_values = [e for e in elements if not e.value] 

Please note I'm using not e.value because I think it reads better and it's more coherent with the variable name not_values but you could also use e.value == 0 .请注意,我使用not e.value是因为我认为它读起来更好,并且与变量名not_values更一致,但您也可以使用e.value == 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 平均列表 A 的所有元素,其索引在列表 B 中具有相同的值 - Average all of elements of list A which whose indices have the same value in list B 如何在整数数组中查找其总和在给定值范围内的所有有序元素对 - How to find all ordered pairs of elements in array of integers whose sum lies in a given range of value 查找值落在 PySpark Dataframe 中特定列之间的所有列的列表 - Find list of all columns whose value fall between specific columns in PySpark Dataframe 如何在列表中找到元素总和最大的列表? - How to find the list in a list of lists whose sum of elements is the greatest? 查找包含特定类的所有html元素 - Find all html elements whose contains a specific class 如何在 python 中找到具有特定值的列表中所有元素的索引 - How to find the index for all the elements in a list with a particular value in python Python:找到list中元素的所有组合达到某个值 - Python: find all combinations of elements in list to reach a certain value 查找并用值替换二维列表中的所有匹配元素 - Find and replace all matching elements in a 2d list with a value 从字典中删除其键是列表元素的所有元素 - Remove all elements from the dictionary whose key is an element of a list 如何扫描一个大列表以查找所有元素是否与第二个较小列表的元素匹配? - How to scan a big list to find if all elements match the ones of a second, smaller, list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM