简体   繁体   中英

Python incrementing array index through loop

Im currently using xlwings to display graphs and their corresponding values in microsoft excel. I have 5 graphs and their coordinates(in an array) that i've successfully been able to print through a loop. Unfortunately the columns in which they appeared in had to be hard coded and would be affected if i were to add more plots, so i changed my code to:

for i in range(1, 6):
    Columns = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S"]

    Range(Columns[0] + str(1)).value = list(zip(Xvalues))
    Range(Columns[1] + str(1)).value = list(zip(Yvalues))

Currently it will take the first plot and print the x-coordinates vertically in Column A("A1") and then the y-coordinates also vertically in Column B("B1") and then continues.

My question is how can i increment the index of Columns[] within the loop so that my next values are Columns[3] and Columns[4]?

You can use another variable to keep track of the column index. In this case j :

Columns = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S"]
j = 1
for j,i in enumerate(range(1, 5)):    
    Range(Columns[j] + str(1)).value = list(zip(Xvalues))
    Range(Columns[j+1] + str(1)).value = list(zip(Yvalues))
    j += 1

Also you should not declare the list of columns within the loop.

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