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

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

问题描述

我有对象列表.我想在此列表中找到一个(第一个或其他)对象,其属性(或方法结果 - 任何)等于 value.

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?

这是测试用例:

  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 it's anywhere near 'Pythonic'
  for x in test_list:
      if x.value == value:
          print "i found it!"
          break
  

我认为使用生成器和 reduce() 不会有任何区别,因为它仍然会遍历列表.

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

ps.: value 的公式只是一个例子.当然我们想要得到满足任何条件的元素.

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)

这会从列表中获取符合条件的第一个项目,如果没有项目匹配,则返回 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.

然而,

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

简单的循环中断版本,是完美的 Pythonic —— 简洁、清晰、高效.使其与单行的行为相匹配:

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

如果您没有 break 退出循环,这会将 None 分配给 x.

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

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

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