简体   繁体   English

如何填写这个python列表?

[英]How to fill up this python list?

I would like to fill up this python list. 我想填写这个python列表。

volume = []
for x in range(0,num_days):
    volume[x] = quotations(x).Volume

I get the error IndexError: list assignment index out of range . 我得到错误IndexError: list assignment index out of range What is wrong with the code and how to fill up volume list? 代码有什么问题以及如何填写volume列表? quotations is an object imported from win2com . quotations是从win2com导入的对象。

I am using python v3.6 我使用的是python v3.6

You have to append as indexing is for setting indices to certain values: 您必须append索引用于将索引设置为特定值:

volume = []
for x in range(0,num_days):
   volume.append(quotations(x).Volume)

In Python, you don't need to "fill up" the list as you would do in static languages like C. The size of the list is automatically managed by the language itself. 在Python中,您不需要像在C等静态语言中那样“填充”列表。列表的大小由语言本身自动管理。 Lists in Python are called lists and not arrays for that very same reason. 由于同样的原因,Python中的列表被称为列表而不是数组。

volume.append(quotations(x).Volume) # instead of volume[x] = quotations(x).Volume

With that said, you can certainly change an element at a certain index if you're sure it's already assigned, which wasn't in your case. 话虽如此,如果您确定已经分配了元素,您当然可以在某个索引处更改元素,这不是您的情况。

您可以使用列表推导来构造volume

volume = [qutations(x).Volume for x in range(0, num_days)]

Change the list to dict 将列表更改为dict

volume = {}
for x in range(0,num_days):
    volume[x] = quotations(x).Volume

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM