这就是你想要做的:
>>> 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