简体   繁体   中英

Python, how to set index properly

I have a question for you.

I have the following code:

defaults = list(0 for m in range(12))
index=6
totale=5
for i in index:
    defaults[i]=totale

But give me error TypeError: 'int' object is not iterable . I want to set the value totale for each month starting from the index untill the end of the year, but the [index:] does not works. In other words I want to obtain the following result:

[0,0,0,0,0,5,5,5,5,5,5,5]

I'm not clear what the variable types are, but you can use a simple for loop

index=month
for i in index:
    fondo_immobbilizzazioni_mat[tipologia][i] = totale

Note, it'll only work if month is of type list/array.

Try with:

for i in range(index, 12):
    defaults[i]=totale

Given the values of index and totale , all you need to do is the following:

defaults = [0] * index + [totale] * (12 - index)

Another option, slightly more complex to read, but (possibly) marginally more memory-effective, since it would not create any temporary lists, would be:

defaults = [0 if i < index else totale for i in range(12)]

It really does not matter much which you use, as long as this line is not called an excessive number of times.

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