0
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')}

所以我有这本字典,显示一个“零件”作为键,值是仓库中的位置。现在假设我想找出货架 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,我发现这是因为所有的值都有不同的长度,那么我该怎么做呢?

4

3 回答 3

1

我不确定你认为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

如另一个答案所示,您可以使用 an 来避免内部循环any,但是对于像这样的复杂条件,很难阅读 imo。

于 2013-11-04T23:39:58.180 回答
0

这就是你想要做的:

>>> 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
于 2013-11-04T23:38:22.223 回答
0

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

>>> 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.
>>>
于 2013-11-04T23:48:22.277 回答