列表理解表过滤

时间:2017-02-23 03:31:47

标签: python list-comprehension

“使用列表推导来过滤小时表以仅包含经理。”

我有两张桌子:小时&标题

hours = [["Alice", 43], ["Bob", 37], ["Fred", 15]]
titles = [["Alice", "Manager"], ["Betty", "Consultant"], ["Bob", "Assistant"]]

我需要将小时表过滤到仅使用列表推导的经理。到目前为止,我已经使用标题创建了一个单独的表,其中包含使用get from toolz

的经理名称
from toolz import get
manager_list = [i for i in titles if get(-1,i) == "Manager"]

产生[['Alice', 'Manager']]

现在我正在尝试使用我的manager_list表并将其与小时表进行比较,以仅在manager_list中保留具有相同名称的条目。但是,我似乎无法弄清楚如何做到这一点。我一直在拿空桌。

我现在所拥有的是manager_hours = [i for i in hours if get(0,i) in manager_list],但它不起作用,我无法弄清楚如何比较两者。

我正在寻找的最终结果是[['Alice', 43]],但我不知道如何到达那里。

3 个答案:

答案 0 :(得分:0)

我会使用一个临时集来自己获取经理,然后过滤:

hours = [["Alice", 43], ["Bob", 37], ["Fred", 15]]
titles = [["Alice", "Manager"], ["Betty", "Consultant"], ["Bob", "Assistant"]]

managers = set(l[0] for l in titles if l[1] == "Manager")

managers
Out[4]: {'Alice'}

manager_hours = [l for l in hours if l[0] in managers]

manager_hours
Out[6]: [['Alice', 43]]

但是,在设计方面,您可能需要考虑使用dict来保存数据。它是键值对的正确数据结构。

答案 1 :(得分:0)

如果数据可能不准确,请使用filter

names = [x for x, y in titles if y == "Manager"]
managers = [(x, y) for (x, y) in hours if x in names]

样本:

>>> names = [x for x, y in titles if y == "Manager"]
>>> names
['Alice']
>>> managers = [(x, y) for (x, y) in hours if x in names]
>>> managers
[('Alice', 43)]

另一种方法,假设您将拥有2个列表,其中包含相同的"名称"以及长度,您可以做的一件事是使用{{1}组合2个列表}。

这样的事情:

zip

答案 2 :(得分:0)

您可以将titles列表设为字典,然后通过查找hours字典来过滤您的title列表:

title_d = dict(titles)    
[i for i in hours if title_d.get(i[0]) == "Manager"]
# [['Alice', 43]]