IndexError:Python 中的列表赋值索引超出范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25407328/
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 20:10:37  来源:igfitidea点击:

IndexError: list assignment index out of range in Python

pythonlist

提问by crax

I was solving a problem in python by using following code:

我正在使用以下代码解决 python 中的问题:

T = int(raw_input()) 
C=[] 
for x in range(T):     
    C[x]=int(raw_input()) 
res=[] 
for x in range(T):     
    res[x]=2**C[x]+2*C-1      
for x in range(T):     
    print "%d\n",(res[x])   

and this error came up:

出现了这个错误:

Traceback (most recent call last):
  File "C:\Users\ACER\Documents\works\source code\python practice\Test1.py", line 4, in <module>
    C[x]=int(raw_input())
IndexError: list assignment index out of range

Can any solve this error pls

任何可以解决这个错误请

采纳答案by Jason Hu

your list is empty. perl will expand array automatically but python won't.

你的清单是空的。perl 会自动扩展数组,但 python 不会。

C.append(int(raw_input()))

instead.

反而。

回答by NPE

You can't expand a Python list by assigning to an element past the end.

您不能通过分配给末尾的元素来扩展 Python 列表。

You need to expand the list explicitly but replacing

您需要显式扩展列表但替换

C[x]=int(raw_input()) 

with

C.append(int(raw_input()))

The same goes for res.

也是如此res

Last but not least, the 2*Cin 2**C[x]+2*C-1will give you a list. It's unclear what you're trying to do here, but 2*Cisn't going to work. Did you mean 2*C[x]?

最后但并非最不重要的,2*Cin2**C[x]+2*C-1会给你一个列表。目前尚不清楚您要在这里做什么,但2*C不会奏效。你的意思是2*C[x]