Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

list - How to create an unknown amount of variables in python

I am making a program that reads a spread sheet. For each column, my program creates a list of all the values in each row of that column. To decide how many lists I need, I have the variable columnBound which is the total amount of columns in the spread sheet. How can I make a program that will sometimes create 3 lists if there are 3 columns and will sometimes create 8 if there are 8 columns?

If there were always 3 columns, for example, I know I could easily have list1, list2, list3, and build them as needed, but how can I have my program build a dynamic number of lists based on columnBound?

It's like I want

for x in range (0, columnBound):
    listx = [] 

Where I would have list1, list2, .... all the way to listx (or listcolumnBound)

I am very new to programming and would love conceptual help, a point in the right direction where. I don't exactly know how to google this question because it is very abstract.

Thanks!

Extra Info:

My program will use the spreadsheet as an input. Each column contains 5 digit reference numbers that correspond to a specific business address. Then, it will take a different spreadsheet where each row has a reference code but needs an address inserted into the last column. I will query each list to see if it has the matching ref code and enter in the respective address into the spreadsheet. Sometimes I will have 5 address columns, sometimes I might have 8. I know that making a program that is explicitly typed (where I specifically create list 1-8 and if there were 9 address columns, the 9th would be left out) is bad practice. I want to learn how to make my program adapt to how many columns there are.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a list of lists:

Eg:

[['col1','col2'],[1,2]]

This way, you can have a dynamic number of lists.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...