2014-02-09 120 views
27

我一直對這個問題感興趣已經兩天了。我是python和編程的新手,所以這種類型的錯誤的其他示例對我沒有太大的幫助。我正在閱讀列表和元組的文檔,但沒有找到任何有用的東西。任何指針都會很感激。沒有必要尋找答案,只是更多的資源在哪裏尋找。我正在使用Python 2.7.6。由於Python的列表索引必須是整數,而不是元組「

measure = raw_input("How would you like to measure the coins? Enter 1 for grams 2 for pounds. ") 

coin_args = [ 
["pennies", '2.5', '50.0', '.01'] 
["nickles", '5.0', '40.0', '.05'] 
["dimes", '2.268', '50.0', '.1'] 
["quarters", '5.67', '40.0', '.25'] 
] 

if measure == 2: 
    for coin, coin_weight, rolls, worth in coin_args: 
     print "Enter the weight of your %s" % (coin) 
     weight = float(raw_input()) 
     convert2grams = weight * 453.592 

     num_coin = convert2grams/(float(coin_weight)) 
     num_roll = round(num_coin/(float(rolls))) 
     amount = round(num_coin * (float(worth)), 2) 

     print "You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll) 

else: 
    for coin, coin_weight, rolls, worth in coin_args: 
     print "Enter the weight of your %s" % (coin) 
     weight = float(raw_input()) 

     num_coin = weight/(float(coin_weight)) 
     num_roll = round(num_coin/(float(rolls))) 
     amount = round(num_coin * (float(worth)), 2) 

     print "You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll) 

這是堆棧跟蹤:

File ".\coin_estimator_by_weight.py", line 5, in <module> 
    ["nickles", '5.0', '40.0', '.05'] 
TypeError: list indices must be integers, not tuple 
+2

你不解析來自'raw_input'結果。它永遠不會是'2'。 –

+1

既然你兩次寫了或多或少相同的源代碼,你應該考慮如何讓它更加優雅。事實上,你的onyl必須區分重量單位,如果需要轉換輸入,其餘的是相同的。 – OBu

+0

OBu非常好。我將致力於完善我的代碼。我假設你正在談論製作一個功能。 – Aaron

回答

46

的問題是,[...]在Python有兩種不同的含義

  1. expr [ index ]意味着訪問列表
  2. [ expr1, expr2, expr3 ]的元素意味着從三個表達式構建三個元素的列表

在您的代碼中,您忘記了通訊對於外部列表中的項目的表達式之間的:

[ [a, b, c] [d, e, f] [g, h, i] ] 

因此Python的解釋第二元素的開始作爲指標將被施加到所述第一和這是錯誤消息在說什麼。

你在找什麼正確的語法是

[ [a, b, c], [d, e, f], [g, h, i] ] 
+3

我很感謝你解釋我得到的錯誤背後的原因。 – Aaron

10

創建列出的名單,你需要將它們用逗號分隔,這樣

coin_args = [ 
    ["pennies", '2.5', '50.0', '.01'], 
    ["nickles", '5.0', '40.0', '.05'], 
    ["dimes", '2.268', '50.0', '.1'], 
    ["quarters", '5.67', '40.0', '.25'] 
] 
6

爲什麼會出現錯誤提的元組?

其他人已經解釋了這個問題是缺少,,但最後的祕密是爲什麼錯誤消息談論元組?

的原因是你的:

["pennies", '2.5', '50.0', '.01'] 
["nickles", '5.0', '40.0', '.05'] 

可以簡化爲:

[][1, 2] 

mentioned by 6502與同樣的錯誤。

但隨後__getitem__,這與[]分辨率交易,轉換object[1, 2]到一個元組:

class C(object): 
    def __getitem__(self, k): 
     return k 

# Single argument is passed directly. 
assert C()[0] == 0 

# Multiple indices generate a tuple. 
assert C()[0, 1] == (0, 1) 

__getitem__的名單落實內置類不能與元組參數那樣對待。

我還建議大家儘量產生最小的例子在未來:-)在__getitem__行動

更多的例子:https://stackoverflow.com/a/33086813/895245

相關問題