在列表中查找具有等于某个值的属性(满足任何条件)的对象 [英] Find object in list that has attribute equal to some value (that meets any condition)

查看:319
本文介绍了在列表中查找具有等于某个值的属性(满足任何条件)的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象列表。我想在此列表中找到一个具有等于的属性(或方法结果 - 任何)的一个(第一个或任何)对象。



找到最好的方法是什么?



这里是测试用例:

  class Test:
def __init __(self,value):
self.value = value

import随机

值= 5

test_list = [范围(1000)中的x的测试(random.randint(0,100))]

#我会在Pascal做的,我不相信在test_list中的Pythonic
附近没有任何地方:
如果x.value == value:
print我发现了!
break

我认为使用生成器和 reduce() code>将不会有任何区别,因为它仍然是通过列表迭代。



ps .:等式为 value 只是一个例子。当然,我们希望得到满足任何条件的元素。

解决方案

  next((x for x in test_list if x.value == value),None)

与条件匹配的列表,如果没有匹配项则返回 None 。这是我首选的单一表达形式。<​​/ p>

但是,

  for x in test_list:
如果x.value ==值:
打印我找到了!
break

天真的循环版本,完美的是Pythonic - 简洁明了,高效。要使匹配一行的行为:

  for x in test_list:
if x.value = = value:
print我发现了!
break
else:
x =无

code>无 x 如果你不 break 循环。


I've got list of objects. I want to find one (first or whatever) object in this list that has attribute (or method result - whatever) equal to value.

What's is the best way to find it?

Here's test case:

  class Test:
      def __init__(self, value):
          self.value = value

  import random

  value = 5

  test_list = [Test(random.randint(0,100)) for x in range(1000)]

  # that I would do in Pascal, I don't believe isn't anywhere near 'Pythonic'
  for x in test_list:
      if x.value == value:
          print "i found it!"
          break

I think using generators and reduce() won't make any difference because it still would be iterating through list.

ps.: Equation to value is just an example. Of course we want to get element which meets any condition.

解决方案

next((x for x in test_list if x.value == value), None)

This gets the first item from the list that matches the condition, and returns None if no item matches. It's my preferred single-expression form.

However,

for x in test_list:
    if x.value == value:
        print "i found it!"
        break

The naive loop-break version, is perfectly Pythonic -- it's concise, clear, and efficient. To make it match the behavior of the one-liner:

for x in test_list:
    if x.value == value:
        print "i found it!"
        break
else:
    x = None

This will assign None to x if you don't break out of the loop.

这篇关于在列表中查找具有等于某个值的属性(满足任何条件)的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆