[英]TypeError: 'float' object is not subscriptable
PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))
PriceList[0][1][2][3][4][5][6]=[PizzaChange]
PriceList[7][8][9][10][11]=[PizzaChange+3]
基本上我有一個輸入,用戶將把一個數字值(浮點輸入)放入其中,然后它將所有這些上述列表索引設置為該值。 出於某種原因,我無法在不提出以下問題的情況下設置它們:
TypeError: 'float' object is not subscriptable
錯誤。 是我做錯了什么還是我只是用錯誤的方式看待它?
PriceList[0]
是一個浮點數。 PriceList[0][1]
正在嘗試訪問浮點數的第一個元素。 相反,做
PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange
或者
PriceList[0:7] = [PizzaChange]*7
PriceList[0][1][2][3][4][5][6]
這說:轉到我的收藏PriceList
的第一個項目。 那東西是一個集合; 得到它的第二個項目。 那東西是一個集合; 得到它的第三...
相反,你想要切片:
PriceList[:7] = [PizzaChange]*7
PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))
for i,price in enumerate(PriceList):
PriceList[i] = PizzaChange + 3*int(i>=7)
您沒有使用 PriceList[0][1][2][3][4][5][6] 選擇多個索引,而是每個 [] 都進入一個子索引。
嘗試這個
PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))
PriceList[0:7]=[PizzaChange]*7
PriceList[7:11]=[PizzaChange+3]*4
看起來您正在嘗試將 PriceList 的元素 0 到 11 設置為新值。 語法通常如下所示:
prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in [0, 1, 2, 3, 4, 5, 6]: PriceList[i] = PizzaChange
for i in [7, 8, 9, 10, 11]: PriceList[i] = PizzaChange + 3
如果它們總是連續的范圍,那么寫起來就更簡單了:
prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in range(0, 7): PriceList[i] = PizzaChange
for i in range(7, 12): PriceList[i] = PizzaChange + 3
作為參考, PriceList[0][1][2][3][4][5][6]
是指“ PriceList
的元素0的元素1的元素2的元素3的元素4的元素5的元素6 . 換句話說,它與((((((PriceList[0])[1])[2])[3])[4])[5])[6]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.