簡體   English   中英

我不斷收到錯誤消息:TypeError: tuple indices must be integers or slice, not str

[英]I keep getting the error: TypeError: tuple indices must be integers or slices, not str

所以我到處都看了,似乎無法得到我理解的答案。 我正在嘗試實現一段代碼,其中 Python 查看一個文本文件,獲取一行,然后查找具有相應名稱的字典。 到目前為止,這是我的代碼:

f = open("data.txt", "r")
  
content = f.readlines()

icecream = {
    "fat": 80,
    "carbohydrates": 50,
    "protein": 650,
    "calories": 45,
    "cholesterol": 50,
    "sodium": 50,
    "name": "Icecream"
}
bigmac = {
    "fat": 29,
    "carbohydrates": 45,
    "protein": 25,
    "sodium": 1040,
    "cholesterol": 75,
    "calories": 540,
    "name": "Big Mac"
  }
whopper = {
    "fat": 47,
    "carbohydrates": 53,
    "protein": 33,
    "sodium": 1410,
    "cholesterol": 100,
    "calories": 760,
    "name": "Whopper"
  }
menu = [
  bigmac,
  whopper,
  icecream
]

sea = content[0]
for line in enumerate(menu):
  if sea.lower() in line['name'].lower():
    print (line['name'])

我不斷收到錯誤TypeError: tuple indices must be integers or slice, not str我不明白為什么。 有人可以幫助我修復我的代碼並可能讓我的 2 個腦細胞理解為什么會出現此錯誤嗎?

enumerate()返回索引和元素的元組。 例如:

>>> for item in enumerate(["a", "b", "c"]):
>>>    print(item)
(0, "a")
(0, "b")
(0, "c")

所以當你枚舉你的menu列表時,你的項目不是這個字典,而是索引和字典的元組。 如果不需要元素索引,請使用:

for line in menu:
    if sea.lower() in line['name'].lower():
        print (line['name'])

如果需要索引,請使用:

for i, line in enumerate(menu):
    if sea.lower() in line['name'].lower():
        print (i, line['name'])

將您的代碼更新為:

for line in menu:
  if sea.lower() in line['name'].lower():
    print (line['name'])

“枚舉”對於已經是數組的菜單是無用的

調用line['name']時會出現錯誤,因為line是由enumerate調用生成的元組:

(0, {'fat': 29, 'carbohydrates': 45, 'protein': 25, 'sodium': 1040, 'cholesterol': 75, 'calories': 540, 'name': 'Big Mac'})
(1, {'fat': 47, 'carbohydrates': 53, 'protein': 33, 'sodium': 1410, 'cholesterol': 100, 'calories': 760, 'name': 'Whopper'})
(2, {'fat': 80, 'carbohydrates': 50, 'protein': 650, 'calories': 45, 'cholesterol': 50, 'sodium': 50, 'name': 'Icecream'})

因此,它需要一個 integer 才能知道要調用哪個menu項。

enumerate(menu) 返回一個“元組” ,而您將其作為字典訪問的方式導致了此錯誤。 此外,如果讀取的字符串中有任何換行符,請使用分割線來處理。

因此,無需枚舉,將代碼更改為如下所示。

sea = content.splitlines()[0]
for line in menu:
  if sea.lower() in line['name'].lower():
    print (line['name'])

這取決於輸入文件數據的方式。 如果這不起作用,請與我們分享輸入文件的外觀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM