简体   繁体   English

在字典中查找特定值,Python

[英]Finding specific values in a dictionary, Python

position={'Part1':('A23-1','A24-2','A24-4','A25-1','A27-5'),
          'Part2':('A26-7','B50-6','C1-3'),
          'Part3':('EM45-4','GU8-9','EM40-3','A15-2')}

So I have this dictionary, showing a "part" as the key and the value being the position in a warehouse. 因此,我有了这个字典,其中显示了一个“部分”作为关键字,而值则是在仓库中的位置。 Now let's say I want to find which parts are on shelf A25 through A27, I've met a wall. 现在,假设我要查找从A25到A27的架子上有哪些零件,我遇到了墙。 So far I've come up with: 到目前为止,我已经提出了:

for part, pos in position:
    if str.split(pos)=='A25' or 'A26' or 'A27':
        print(part,'can be found on shelf A25-A27')

However, this gives me a ValueError, which I've found to be 'cause all of the values have different lengths, so how do I go about this? 但是,这给了我一个ValueError,我发现这是因为所有值都有不同的长度,那么我该如何处理呢?

I'm not sure what you think str.split(pos) is going to do, but probably not what you want. 我不确定您认为str.split(pos)会做什么,但可能不是您想要的。 :) :)

Similarly, if foo == 1 or 2 doesn't check whether foo is either of those values; 同样, if foo == 1 or 2 ,则不检查foo是否为这些值之一; it's parsed as (foo == 1) or 2 , which is always true because 2 is a true value. 它被解析为(foo == 1) or 2 ,因为2为真值,所以始终为真。 You want foo in (1, 2) . 您想要foo in (1, 2)

You're also trying to loop over position alone, which gives you only the keys; 您还试图单独循环position ,这只给您钥匙。 that's probably the source of your error. 这可能是您错误的根源。

The values in your dictionary are themselves tuples, so you need a second loop: 字典中的值本身就是元组,因此需要第二个循环:

for part, positions in position.items():
    for pos in positions:
        if pos.split('-')[0] in ('A25', 'A26', 'A27'):
            print(part, "can be found on shelves A25 through A27")
            break

You could avoid the inner loop with an any as shown in the other answer, but imo that's hard to read with a complex condition like this one. 您可以避免使用另一个答案中所示的any来避免内部循环,但是imo在像这样的复杂条件下很难阅读。

This is what you're trying to do: 这是您要执行的操作:

>>> position={'Part1':('A23-1','A24-2','A24-4','A25-1','A27-5'),
...           'Part2':('A26-7','B50-6','C1-3'),
...           'Part3':('EM45-4','GU8-9','EM40-3','A15-2')}
>>> for part,pos in position.items():
...     if any(p.split('-',1)[0] in ["A%d" %i for i in range(25,28)] for p in pos):
...             print(part,'can be found on shelf A25-A27')
... 
Part1 can be found on shelf A25-A27
Part2 can be found on shelf A25-A27

But I'm going to suggest that you transform your data structure a little: 但是我建议您稍微改变一下数据结构:

>>> positions = {}
>>> for item,poss in position.items():
...     for pos in poss:
...         shelf, col = pos.split('-')
...         if shelf not in positions:
...             positions[shelf] = {}
...         if col not in positions[shelf]:
...             positions[shelf][col] = []
...         positions[shelf][col].append(item)
... 

Now you can do this: 现在您可以执行以下操作:

>>> shelves = "A25 A26 A27".split()
>>> for shelf in shelves:
...     for col in positions[shelf]:
...         for item in positions[shelf][col]:
...             print(item, "is on shelf", shelf)
... 
Part1 is on shelf A25
Part2 is on shelf A26
Part1 is on shelf A27

Here is an efficient one-line solution: 这是一种有效的单行解决方案:

>>> position = {'Part1':('A23-1','A24-2','A24-4','A25-1','A27-5'),
...             'Part2':('A26-7','B50-6','C1-3'),
...             'Part3':('EM45-4','GU8-9','EM40-3','A15-2')}
>>> lst = [k for k,v in position.items() if any(x.split('-')[0] in ('A25', 'A26', 'A27') for x in v)]
>>> lst
['Part2', 'Part1']
>>>
>>> for x in sorted(lst):
...     print(x,'can be found on shelf A25-A27.')
...
Part1 can be found on shelf A25-A27.
Part2 can be found on shelf A25-A27.
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM