在列表中查找具有某个属性等于某个值(满足任何条件)的对象。
在列表中查找具有某个属性等于某个值(满足任何条件)的对象。
我有一个对象列表。我想找到其中一个(第一个或其他)属性(或方法结果-随意)等于value
的对象。
找到它的最佳方法是什么?
这里是一个测试用例:
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()
没有任何区别,因为它仍然会迭代列表。
ps.:value
等式只是一个例子。当然,我们想要获得满足任何条件的元素。
admin 更改状态以发布 2023年5月22日
由于它还没有被提及,这里只是为了完成而提到。
函数式编程很棒。
####### Set Up ####### class X: def __init__(self, val): self.val = val elem = 5 my_unfiltered_list = [X(1), X(2), X(3), X(4), X(5), X(5), X(6)] ####### Set Up ####### ### Filter one liner ### filter(lambda x: condition(x), some_list) my_filter_iter = filter(lambda x: x.val == elem, my_unfiltered_list) ### Returns a flippin' iterator at least in Python 3.5 and that's what I'm on print(next(my_filter_iter).val) print(next(my_filter_iter).val) print(next(my_filter_iter).val) ### [1, 2, 3, 4, 5, 5, 6] Will Return: ### # 5 # 5 # Traceback (most recent call last): # File "C:\Users\mousavin\workspace\Scripts\test.py", line 22, in# print(next(my_filter_iter).value) # StopIteration # You can do that None stuff or whatever at this point, if you don't like exceptions.
我知道通常在Python中,列表推导式更受欢迎,或者至少是从我读到的内容来看是这样。但是,说实话我并不认为这是个问题。当然Python不是一种FP语言,但Map/Reduce/Filter非常易读,并且是FP中最常用的标准用例。
所以,你可以去了解一下函数式编程。
过滤器条件列表。
它不会比这更简单:
next(filter(lambda x: x.val == value, my_unfiltered_list)) # Optionally: next(..., None) or some other default value to prevent Exceptions
next((x for x in test_list if x.value == value), None)
这个函数从列表中获取第一个满足条件的项目,并且在没有项目匹配的情况下返回None
。它是我首选的单个表达式形式。
然而,
for x in test_list: if x.value == value: print("i found it!") break
简单的循环中断版本,完全符合Pythonic-它简洁,清晰和高效。为了使它与单行代码的行为相匹配:
for x in test_list: if x.value == value: print("i found it!") break else: x = None
如果您不break
退出循环,这将为x
分配None
。