Python - “元组索引超出范围”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13903427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:54:07  来源:igfitidea点击:

Python - "tuple index out of range"

pythonindexing

提问by keirbtre

I am writing a program to display information about countries in a table format. It worked perfectly fine when I had 3 countries, but changing it to 10 (and adjusting all necessary code accordingly) resulted in the error, "Tuple index out of range" in the line:

我正在编写一个程序,以表格格式显示有关国家的信息。当我有 3 个国家时,它工作得很好,但是将其更改为 10(并相应地调整所有必要的代码)导致错误,“元组索引超出范围”行中:

print("{0:^20}{1:^20}{2:^20}{3:^20}{4:^20}{5:^20}[6:^20}{7:^20}{8:^20}{9:^20}".format(newcountrylist[i].country,newcountrylist[i].currency,newcountrylist[i].exchange))

采纳答案by Martijn Pieters

You need to pass in a matching number of arguments for your format slots. Your format string has 10 slots, but you are only passing in 3 values.

您需要为格式槽传递匹配数量的参数。您的格式字符串有 10 个插槽,但您只传递了 3 个值。

Reduced to 4 format slots, with only 3 arguments to .format(), shows the same error:

减少到 4 个格式槽,只有 3 个参数给.format(),显示相同的错误:

>>> '{0:^20}{1:^20}{2:^20}{3:^20}'.format(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> '{0:^20}{1:^20}{2:^20}{3:^20}'.format(1, 2, 3, 4)
'         1                   2                   3                   4          '

When I passed in 4 arguments the .format()call succeeds.

当我传入 4 个参数时,.format()调用成功。

回答by oneindelijk

As an aswer to jon141: I'm also facing this issue and I'm trying to solve this by looping over one item of a column (I'm passing a 2 dimensional array) and then building the string based on that. So I end up with a string like

作为对 jon141 的回答:我也面临这个问题,我试图通过循环一列的一项(我正在传递一个二维数组)然后基于它构建字符串来解决这个问题。所以我最终得到一个字符串

template="{0!s:10}{1!s:15}...{n!s:24}

The elements I want to format I put in a tuple. but when I do

我想格式化的元素放在一个元组中。但是当我这样做的时候

template.format(tuple_variable)

it throws an error that the tuple index is out of range

它抛出元组索引超出范围的错误

Probably because it's now passing a tuple of a tuple to the function, which has one element, the tuple

可能是因为它现在将元组的元组传递给函数,该函数具有一个元素,即元组

I haven't figured out how to fix that yet, but follow the threadif you need more info on it.

我还没有想出如何解决这个问题,但 如果你需要更多信息,请关注线程