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,我发现'因为所有的值都有不同的长度,所以我该怎么做呢?
答案 0 :(得分: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
你可以避免使用any
的内部循环,如另一个答案中所示,但imo很难用这样的复杂条件阅读。
答案 1 :(得分: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
答案 2 :(得分: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.
>>>