Python中的元组dict-key匹配的一个元素 [英] One element of a tuple dict-key matching in Python

查看:541
本文介绍了Python中的元组dict-key匹配的一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个dict,例如:

If I have a dict such as:

foo = {('foo', 45):5, ('bar', 34):3}

如何检查该元组的一部分? >

How can I check against part of that tuple?

if 'foo' in foo: #should be true
    pass
if 45 in foo: #also should be true

或其他一些语法。

推荐答案

>>> foo = {('foo', 45): 5, ('bar', 34): 3}    
>>> any(t1 == "foo" for (t1, t2) in foo)
True    
>>> any(t2 == 45 for (t1, t2) in foo)
True

如果你不知道在哪里找到你可以检查整个对:

If you don't know where the value is to be found you can just check the whole pair:

>>> any(45 in pair for pair in foo)
True

您还可以使用生成器方法( flatten ):

You can also a generators approach (flatten):

>>> 45 in flatten(foo)
True

可以说最好的主意是建立你的数据,所以你可以在O(1)时间(一套?重构的字典?)中检查这种包容性。

That said, probably the best idea is to build your data so you can check this kind of inclussion in O(1) time (a set? a refactored dictionary?)

这篇关于Python中的元组dict-key匹配的一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆