Python - 从数组中选择具有某些属性的单个元素

时间:2014-08-28 20:13:44

标签: python arrays list-comprehension

我现在遇到过几次这样的情况:我有一个包含我想要的元素的数组,我想在不知道索引的情况下选择该元素,而是知道一些所需的属性(也许它是一个字典列表我希望字典elem使elem['foo'] == 'bar')。

我有一个解决方案是做一个过滤器(或更多的pythonically,一个列表理解),然后采取第一个元素(通常我知道过滤后的列表将是一个单例,所以采取第一个是唯一的)。

实施例。给定列表x = [{'foo': 'bar_1'}, {'foo': 'bar_2'}],我想要'foo'值为'bar2'的元素。所以我这样做:

y = [elem for elem in x if elem['foo'] == 'bar_2'][0]

有更标准的方法吗?这似乎是一个非常简单和常见的用例。

2 个答案:

答案 0 :(得分:1)

如果您经常遇到此问题,请考虑使用其他数据结构。考虑一个dicts列表是否真的是您正在解决的问题的最佳数据结构。或者,如果是,请添加dict以跟踪您需要的信息。在这种情况下,在构建x时,还要构建index

index = {'bar2':x[1], 'bar1':x[0]}

Dict lookups are O(1),而任何基于列表的查找都是O(n)

答案 1 :(得分:1)

您可以使用generator来电next来获得第一场比赛:

l = [{'foo': 'bar_1'}, {'foo': 'bar_2'}]
print next(d for d in l if d["foo"] == "bar_2")
{'foo': 'bar_2'}

d = (d for d in l if d["foo"] == "bar_2")
first = next(d)

你也可以itertools.dropwhile,如果你想要前两个元素:

In [52]: from itertools import dropwhile,takewhile
In [53]: l = [{'foo': 'bar_1'}, {'foo': 'bar_2'},{'foo': 'bar_2',"goo":"bar"}]
In [54]: d = dropwhile(lambda x: x["foo"] != "bar_2",l)   # drop elements whose where value of key "foo" is not equal to "bar_2"
In [55]: first = next(d)
In [56]: second = next(d)    
In [57]: first
Out[57]: {'foo': 'bar_2'}    
In [58]: second
Out[58]: {'foo': 'bar_2', 'goo': 'bar'}