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

So I've looked all over the place and cant seem to get an answer that I understand.所以我到处都看了,似乎无法得到我理解的答案。 I am trying to implement a piece of code where Python looks at a text file, gets a line, and looks for a dictionary with a corresponding name.我正在尝试实现一段代码,其中 Python 查看一个文本文件,获取一行,然后查找具有相应名称的字典。 Here is my code so far:到目前为止,这是我的代码:

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'])

I keep getting the error TypeError: tuple indices must be integers or slices, not str and I don't understand why.我不断收到错误TypeError: tuple indices must be integers or slice, not str我不明白为什么。 Could someone help me fix my code and possibly get my 2 brain-cells to understand why this error comes up?有人可以帮助我修复我的代码并可能让我的 2 个脑细胞理解为什么会出现此错误吗?

enumerate() returns a tuple of index and element. enumerate()返回索引和元素的元组。 Eg:例如:

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

So when you enumerate over your menu list, your item is not this dict, but tuple of index and dict.所以当你枚举你的menu列表时,你的项目不是这个字典,而是索引和字典的元组。 If you don't need index of element, use:如果不需要元素索引,请使用:

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

If you need index, use:如果需要索引,请使用:

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

Update your code to:将您的代码更新为:

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

"enumerate" is useless with menu that is already an array “枚举”对于已经是数组的菜单是无用的

Your error arises when calling line['name'] , as line is a tuple produced by the enumerate call:调用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'})

As such, it will need a integer in order to know which of menu 's items to call.因此,它需要一个 integer 才能知道要调用哪个menu项。

enumerate(menu) returns a "tuple" and the way you were accessing it as a dictionary has caused this error. enumerate(menu) 返回一个“元组” ,而您将其作为字典访问的方式导致了此错误。 Also, use splitlines to handle if there is any new-line characters in the read string.此外,如果读取的字符串中有任何换行符,请使用分割线来处理。

So, change the code as below without enumerate.因此,无需枚举,将代码更改为如下所示。

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

This depends on how the input file data is.这取决于输入文件数据的方式。 Share us how the input file looks like, if this is not working.如果这不起作用,请与我们分享输入文件的外观。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我不断收到此错误:TypeError: tuple indices must be integers or slices, not tuple - I keep getting this error: TypeError: tuple indices must be integers or slices, not tuple 我不断收到此错误:列表索引必须是整数或切片,而不是 str - I keep getting this error: list indices must be integers or slices, not str 类型错误:元组索引必须是整数或切片,而不是 str - TypeError: tuple indices must be integers or slices, not str 我对字符串和整数有些困惑,并且不断收到此错误:TypeError:列表索引必须是整数或切片,而不是str - I'm a little confused with strings and integers, and I keep getting this error: TypeError: list indices must be integers or slices, not str 我发生了错误异常:TypeError 元组索引必须是整数或切片,而不是 str (Open CV)? - i had Error Exception has occurred: TypeError tuple indices must be integers or slices, not str (Open CV)? 为什么会出现此错误:TypeError:元组索引必须是整数或切片,而不是str - Why do I get this error: TypeError: tuple indices must be integers or slices, not str 收到错误:TypeError:列表索引必须是整数或切片,而不是元组 - Getting the error : TypeError: list indices must be integers or slices, not tuple 我为什么会收到此错误TypeError:列表索引必须是整数或切片,而不是str - Why am I getting this error TypeError: list indices must be integers or slices, not str TypeError:元组索引必须是整数或切片,而不是str Python情绪鸣叫 - TypeError: tuple indices must be integers or slices, not str Python sentiment tweet TypeError:元组索引必须是整数或切片,而不是命令中的str - TypeError: tuple indices must be integers or slices, not str in command
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM