Python 列表理解表过滤

Python 列表理解表过滤,python,list-comprehension,Python,List Comprehension,“使用列表理解来筛选工时表,使其仅包括经理。” 我有两张桌子:时间和标题 hours = [["Alice", 43], ["Bob", 37], ["Fred", 15]] titles = [["Alice", "Manager"], ["Betty", "Consultant"], ["Bob", "Assistant"]] 我需要使用列表将工时表向下过滤到只有经理。到目前为止,我已经使用标题创建了一个单独的表,其中包含使用get from toolz的经理的姓名 from toolz

“使用列表理解来筛选工时表,使其仅包括经理。”

我有两张桌子:时间和标题

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_列表表与hours表进行比较,以便在manager_列表中只保留名称相同的条目。然而,我似乎不知道该怎么做。我总是得到空桌子

我现在拥有的是
manager\u hours=[I for I in hours if get(0,I)in manager\u list]
,但它不起作用,我不知道如何比较这两个


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

我会使用一个临时集合来获取经理,然后根据该集合进行筛选:

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
s保存数据。它是键值对的正确数据结构。

如果数据可能不准确,请使用
过滤器

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

另一种方法是,假设两个列表具有相同的“名称”集和长度,可以使用
zip
组合这两个列表

大概是这样的:

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

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

您可以将
标题
列表设置为字典,然后通过查找
标题
字典来筛选
小时数
列表:

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

很高兴这有帮助。如果答案有用,请将答案标记为已接受。答案旁边的“绿色记号”对您的帮助最大。
title_d = dict(titles)    
[i for i in hours if title_d.get(i[0]) == "Manager"]
# [['Alice', 43]]