2013-11-04 115 views
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上的哪些部件,我遇到了一堵牆。到目前爲止,我想出了:查找字典中的特定值,Python

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

然而,這給了我一個ValueError,我已經發現「使所有的值有不同的長度,所以我怎麼去呢?

回答

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內循環,如圖中的其他答案,但海事組織這是很難與閱讀像這樣的複雜情況。

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