简体   繁体   中英

How to fill up this python list?

I would like to fill up this python list.

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

I get the error IndexError: list assignment index out of range . What is wrong with the code and how to fill up volume list? quotations is an object imported from win2com .

I am using python v3.6

You have to append as indexing is for setting indices to certain values:

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. Lists in Python are called lists and not arrays for that very same reason.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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