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
304 views
in Technique[技术] by (71.8m points)

Python - efficient way to create 20 variables?

I need to create 20 variables in Python. That variables are all needed, they should initially be empty strings and the empty strings will later be replaced with other strings. I cann not create the variables as needed when they are needed because I also have some if/else statements that need to check whether the variables are still empty or already equal to other strings.

Instead of writing

variable_a = ''
variable_b = ''
....

I thought at something like

list = ['a', 'b']
for item in list:
    exec("'variable_'+item+' = '''")

This code does not lead to an error, but still is does not do what I would expect - the variables are not created with the names "variable_1" and so on.

Where is my mistake?

Thanks, Woodpicker

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Where is my mistake?

There are possibly three mistakes. The first is that 'variable_' + 'a' obviously isn't equal to 'variable_1'. The second is the quoting in the argument to exec. Do

for x in list:
    exec("variable_%s = ''" % x)

to get variable_a etc.

The third mistake is that you're not using a list or dict for this. Just do

variable = dict((x, '') for x in list)

then get the contents of "variable" a with variable['a']. Don't fight the language. Use it.


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

...