【问题标题】:"Tuple index out of range" Error?“元组索引超出范围”错误?
【发布时间】:2016-09-27 23:09:35
【问题描述】:

我不确定我在这里做错了什么,有人知道吗?我不断收到一条错误消息,提示“元组索引超出范围”。我正在学习学校的教程,我似乎做的一切都是正确的,但是我一直收到这个错误。任何帮助,将不胜感激!非常感谢。

animal = input("Enter any LARGE animal: ")
smallAnimal = input("Enter any SMALL animal: ")
weapon = input("Enter a sharp weapon: ")

def createDictionary():

    storyDict = dict()
    storyDict['animal'] = animal
    storyDict['smallAnimal'] = smallAnimal
    storyDict['weapon'] = weapon

return storyDict

def main():

    dictionary = createDictionary()

    animalFormat = """Once upon a time, there was a very, very large {animal}. This {animal} was the meanest, baddest, most gruesome {animal} there     was. And one day, a wild {1} had
    stepped on the {animal}'s foot. At that moment, the {1} knew it had messed up. This made the {animal} angry, so he took a {weapon} and STABBED the 
    {smallAnimal}with it! The {smallAnimal} squirmed and fought to get out, but it was no match for the {animal} with a {weapon}.

    The End."""

    withSubstitutions = animalFormat.format(**dictionary)
    print(withSubstitutions)


main()

【问题讨论】:

  • 错误发生在哪里?你提供什么作为输入?
  • 什么是storyDict = dict()?不是 storyDict = {}?
  • Scott,错误发生在 withSubstitutions = animalFormat.format(**dictionary)。我正在尝试使用用户输入的动物、小动物和武器来打印故事。如果这就是你要问的。
  • Omid,storyDict = dict() 是我被教导制作字典的方式。对吗?
  • @Sammy 没有。使用 dicts = {} 创建一个新的字典。此外,与其让多行分配值,不如像这样创建和初始化字典? def get_dict(): return {'animal': animal, 'smallAnimal': smallAnimal, 'weapon', weapon}。更少打字 = 更好。

标签: python tuples


【解决方案1】:

在animalFormat中,替换:

{1}

与:

{smallAnimal}

必须在两个地方进行此更改。

由于您使用关键字向format 提供参数,因此1 没有可引用的内容。

更简单的例子

请注意这是有效的:

>>> d = {'a':1, 'b':2}
>>> 'Twice {a} is {b}'.format(**d)
'Twice 1 is 2'

但这不起作用:

>>> 'Twice {1} is {b}'.format(**d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

如果您为 format 提供关键字参数,则 1 没有可参考的内容。

可以同时提供位置参数和关键字参数。例如:

>>> 'Twice {1} is {b}'.format('Arg0', 'ArgOne', **d)
'Twice ArgOne is 2'

完整的工作代码

animal = input("Enter any LARGE animal: ")
smallAnimal = input("Enter any SMALL animal: ")
weapon = input("Enter a sharp weapon: ")

def createDictionary():

    storyDict = dict()
    storyDict['animal'] = animal
    storyDict['smallAnimal'] = smallAnimal
    storyDict['weapon'] = weapon

    return storyDict

def main():

    dictionary = createDictionary()

    animalFormat = """Once upon a time, there was a very, very large {animal}. This {animal} was the meanest, baddest, most gruesome {animal} there     was. And one day, a wild {smallAnimal} had
    stepped on the {animal}'s foot. At that moment, the {smallAnimal} knew it had messed up. This made the {animal} angry, so he took a {weapon} and STABBED the_
    {smallAnimal}with it! The {smallAnimal} squirmed and fought to get out, but it was no match for the {animal} with a {weapon}.

    The End."""

    withSubstitutions = animalFormat.format(**dictionary)
    print(withSubstitutions)


main()

示例运行:

Enter any LARGE animal: Lion
Enter any SMALL animal: Mouse
Enter a sharp weapon: knife
Once upon a time, there was a very, very large Lion. This Lion was the meanest, baddest, most gruesome Lion there     was. And one day, a wild Mouse had
    stepped on the Lion's foot. At that moment, the Mouse knew it had messed up. This made the Lion angry, so he took a knife and STABBED the 
    Mousewith it! The Mouse squirmed and fought to get out, but it was no match for the Lion with a knife.

    The End.

【讨论】:

  • 约翰您好,感谢您指出这一点。我正在编辑旧代码并忘记删除 {1}。但是,我仍然收到错误消息。
  • @Sammy 你必须在两个地方都消除它。在我这样做之后,你的代码对我有用。
  • 哇,非常感谢。我只是犯了一个愚蠢的错误。非常有用的建议,非常感谢约翰!
【解决方案2】:

您正在通过关键字和有序数据混淆格式化字符串。

MCVE:

s = "{0}{k}".format(k='something')

例外:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

由于您的模板包含有序参数的占位符 ({1}),您需要将它们传递给您的函数:

animalFormat = """Once upon a time, there was a very, very large {animal}. This {animal} was the meanest, baddest, most gruesome {animal} there     was. And one day, a wild {1} had
stepped on the {animal}'s foot. At that moment, the {1} knew it had messed up. This made the {animal} angry, so he took a {weapon} and STABBED the 
{smallAnimal}with it! The {smallAnimal} squirmed and fought to get out, but it was no match for the {animal} with a {weapon}.

The End."""

d = {'animal': 'X', 'smallAnimal': 'Y', 'weapon': 'Z'}
a = ['A', 'B']  # placeholder
animalFormat.format(*a, **d)  # works fine

【讨论】:

  • 您好,感谢您的详细回复。我并不是要在我的代码中包含 {1},我正在编辑旧代码并忘记用 smallAnimal 替换它。在我替换它之后,我仍然得到错误。知道为什么吗?
【解决方案3】:

此错误是因为您有命名替换(例如.. very large {animal} ..)以及位置替换(例如At that moment, the {1} knew ..)。

考虑传递类似的东西:

animalFormat.format("Replacement for {0}", "Replacement for {1}", **dictionary)

在上述情况下,替换的位置部分将显示为:

At the moment, the Replacement for {1} knew ..

【讨论】:

  • 感谢您的回复!它已被修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多