繁体   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