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