搜索两个词典中的项目并根据匹配返回结果

时间:2017-09-10 10:37:49

标签: python performance dictionary search

co_1 = {'a1': [(1, 1)], 'b1': [(0, 4), (0, 0), (4, 0)]}
co_2 = {'a2': [(2, 2)], 'b2': [(1, 5), (1, 2), (5, 1)]}

position = (x, y)

如何检查两个词典&co; co_1和co_2'的值中是否存在位置(例如(1,5))。

到目前为止,我有:

for key, value in co_1.items():
    if position in value:
        return (statement1)
for key, value in co_1.items():
    if position in value:
        return(statement2)
#if position not in either value --> return None

有没有办法清理它,所以我可以一起搜索两个词典中的位置,然后有一个if-else语句:如果值(co_1或co_2)中的位置返回(语句),则返回None。

如:

for key, value in co_1.items() and co_2.items():
    if position in value in co_1.items():
        return statement1
    elif position in value in co_2.items():
        return statement2
    else:
        return None
#example if position = (2, 2) --> return statement2
#exmaple if position = (3, 1) --> return None

5 个答案:

答案 0 :(得分:2)

这里的键似乎不相关 - 你可以从这两个词典中构建一组元组。

co_1_set = {y for x in co_1 for y in co_1[x] } 
co_2_set = {y for x in co_2 for y in co_2[x] } 

现在,成员资格测试就像if-elif语句一样简单:

def foo(position):
    if position in co_1_set:
        return statement1

    elif position in co_2_set:
        return statement2

您希望尽可能少地执行set构造 - 理想情况下,只有在字典内容发生变化时才会这样做。

如果您的词典都包含position,则此代码仅返回statement1。如果您想要不同的东西,则需要进行适当的更改。

答案 1 :(得分:0)

您可以使用每个字典的扁平值,如下所示:

co_1 = {'a1': [(1, 1)], 'b1': [(0, 4), (0, 0), (4, 0)]}
co_2 = {'a2': [(2, 2)], 'b2': [(1, 5), (1, 2), (5, 1)]}

def check_position(pos):
    if pos in [item for sublist in co_1.values() for item in sublist]:
        return 'statement1'
    elif pos in [item for sublist in co_2.values() for item in sublist]:
        return 'statement2'
    else:
        return None

pos1 = (2, 2)
pos2 = (0, 4)

print(check_position(pos1))  # Output: statement2
print(check_position(pos2))  # Output: statement1

答案 2 :(得分:0)

另一种方式:sum(pos in v for v in arg.values())是返回0的会员资格测试,当找不到False时== pos

在下面用作列表理解中的条件,返回输入enumerate的{​​{1}}索引

*args

答案 3 :(得分:0)

你可以使用2布尔变量

co_1 = {'a1': [(1, 1)], 'b1': [(0, 4), (0, 0), (4, 0)]}
co_2 = {'a2': [(1, 2)], 'b2': [(1, 5), (1, 2), (5, 1)]}
position = (1,1)

tco1=False
tco2=False
for key, value in co_1.items():
    if position in value:
        tco1=True

for key, value in co_2.items():
    if position in value:
        tco2=True
if tco1==True:
    print("Statement 1") #Or return Statement 1
elif tco2==True:
    print("Statement 2") #Or return Statement 2
else :
    print("None") #Or return None

答案 4 :(得分:-1)

尝试使用generator:

def search(item, co_1, co_2):
    co_1_values = co_1.values()
    co_2_values = co_2.values()
    for value in list(co_1_values) + list(co_2_values):
        yield 'statement1' if item in value in co_1_values else ''
        yield 'statement2' if item in value in co_2_values else ''

在这种情况下,您将收到所有已发现的陈述。

如果您只需要首次出现:

for item in search((1, 1), co_1, co_2):
    if item.strip():
        print(item)
        break