python列表目录

python列表目录,python,list,dictionary,Python,List,Dictionary,我的意见如下: items_temp = dict(fruits=["apple", "orange"], vegetables=["carrot", "potato"], animals=["dog", "cat"]) 下面的列表需要验证它包含什么样的东西 check = ["orange", "dog", "apple"] 有没有什么灵巧的Python方法可以从上面的数据中获得下面的dict output = dict(fruits = ["orange", "apple"], anim

我的意见如下:

items_temp = dict(fruits=["apple", "orange"], vegetables=["carrot", "potato"], animals=["dog", "cat"])
下面的列表需要验证它包含什么样的东西

check = ["orange", "dog", "apple"]
有没有什么灵巧的Python方法可以从上面的数据中获得下面的dict

output = dict(fruits = ["orange", "apple"], animals=["dog"])

我认为你应该能够做到以下几点:

check = set(['orange', 'dog', 'apple'])
output = {k: check.intersection(v) for k, v in items_temp.items() if check.intersection(v)}
基本上,我是在检查
check
和字典值之间的交叉点。如果存在交点,我们将其添加到输出中

这将为您提供一个以集合为值的字典,但是您可以非常轻松地转换它


注意,我们正在进行两次交叉点检查。如果我们在处理管道中添加一个额外的步骤,那就有点烦人了(我们当然不需要这样做)

check = set(['orange', 'dog', 'apple'])
keys_intersect = ((k, check.intersection(v)) for k, v in items_temp.iteritems())
output = {k: intersect for k, intersect in keys_intersect if intersect}

没有一种简单、一步到位的方法可以实现您的目标,但您可以通过两种方式实现:

>>> output = {k:[v for v in vs if v in check] for k,vs in items_temp.items()}
>>> output
{'vegetables': [], 'animals': ['dog'], 'fruits': ['apple', 'orange']}
接下来,我们只需要过滤掉空列表:

>>> output = {k:vs for k,vs in output.items() if vs}
>>> output
{'animals': ['dog'], 'fruits': ['apple', 'orange']}
如果要检查的项目很多,可以通过将
check
转换为
set
来大大加快速度,但过早优化是万恶之源

编辑:我想你可以一次完成:

>>> output = {k:[v for v in vs if v in check] for k,vs in items_temp.items() if any(v in check for v in vs)}
>>> output
{'animals': ['dog'], 'fruits': ['apple', 'orange']}
但这让冗余测试变得过于复杂

你也可以这样做

{k:vs for k,vs in ((k,[v for v in vs if v in check]) for k,vs in items_temp.items()) if vs}

一步到位,而不需要重复的成员资格检查,但现在我们有点傻了。

为什么不使用字典呢

a={"Mobin":"Iranian","Harry":"American"}
您可以通过以下方式获得:

print a.get("Mobin")

运行此代码时,您可以在屏幕中看到“Iranian”(伊朗语),它实际上将
v
添加到输出,而不是交叉点。您应该假设Python 3没有
iteritems
。如果您的dict从
“apple”
转到
“fruit”
,而不是
“fruits”
转到
[“apple”,“orange”]
,那么这个操作会更有效。当
检查=[“orange”,“dog”]
时,您想要什么输出?您希望结果中的
fruts
[“橙色”]
还是
[“橙色”,“苹果”]
?@Hamms基于
动物(其中包含
“猫”
),只要
[“橙色”]
。这就是我没有将示例dict一直向右滚动得到的结果:P@RoadieRich:提问者可能控制了dict的格式,或者提问者可以转换dict一次,然后使用更有效的表示法重复执行此操作。