在字典中查找特定值,Python

2024-06-01 06:55:42 发布

您现在位置: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')}

所以我有一本字典,显示一个“part”作为键,值是仓库中的位置。现在让我们假设我想找出哪些零件在A25到A27架子上,我遇到了一堵墙。到目前为止,我想到了:

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

但是,这给了我一个ValueError,我发现它是'因为所有的值都有不同的长度,所以我该怎么做呢?你知道吗


Tags: orpospositionpart2part1partc1part3
3条回答

下面是一个有效的单线解决方案:

>>> 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.
>>>

这就是你想要做的:

>>> 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

但我建议您稍微改变一下数据结构:

>>> 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)
... 

现在您可以这样做:

>>> 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

我不确定你认为str.split(pos)会做什么,但可能不是你想要的。:)

类似地,if foo == 1 or 2不检查foo是否是这些值中的任何一个;它被解析为(foo == 1) or 2,这始终是真的,因为2是真值。你想要foo in (1, 2)。你知道吗

您还试图单独在position上循环,这只提供了密钥;这可能是您的错误的根源。你知道吗

字典中的值本身就是元组,因此需要第二个循环:

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

您可以使用any避免内部循环,如另一个答案中所示,但是对于这样的复杂条件,这很难理解。你知道吗

相关问题 更多 >