How do you create different variable names while i

2019-01-01 00:33发布

问题:

For example purposes...

for x in range(0,9):
    string\'x\' = \"Hello\"

So I end up with string1, string2, string3... all equaling \"Hello\"

回答1:

Sure you can; its called a dictionary:

d={}
for x in range(1,10):
        d[\"string{0}\".format(x)]=\"Hello\"

In [7]: d[\"string5\"]
Out[7]: \'Hello\'

In [8]: d
Out[8]: 
{\'string1\': \'Hello\',
 \'string2\': \'Hello\',
 \'string3\': \'Hello\',
 \'string4\': \'Hello\',
 \'string5\': \'Hello\',
 \'string6\': \'Hello\',
 \'string7\': \'Hello\',
 \'string8\': \'Hello\',
 \'string9\': \'Hello\'}

I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!



回答2:

It is really bad idea, but...

for x in range(0, 9):
    globals()[\'string%s\' % x] = \'Hello\'

and then for example:

print(string3)

will give you:

Hello

However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to know how to do it, but did not want to use it.



回答3:

It\'s simply pointless to create variable variable names. Why?

  • They are unnecessary: You can store everything in lists, dictionarys and so on
  • They are hard to create: You have to use exec or globals()
  • You can\'t use them: How do you write code that uses these variables? You have to use exec/globals() again

Using a list is much easier:

# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = [\"Hello String %d\" % x for x in range(9)]
for string in strings: # you can loop over them
    print string
print string[6] # or pick any of them


回答4:

Don\'t do this use a dictionary

import sys
this = sys.modules[__name__] # this is now your current namespace
for x in range(0,9):
    setattr(this, \'string%s\' % x, \'Hello\')

print string0
print string1
print string2
print string3
print string4
print string5
print string6
print string7
print string8

don\'t do this use a dict

globals() has risk as it gives you what the namespace is currently pointing to but this can change and so modifying the return from globals() is not a good idea



回答5:

One way you can do this is with exec(). For example:

for k in range(5):
    exec(f\'cat_{k} = k*2\')

print(cat_0)
0
print(cat_1)
2
print(cat_2)
4
print(cat_3)
6
print(cat_4)
8

Here I am taking advantage of the handy f string formatting in python 3.6+



回答6:

I would use a list:

string = []
for i in range(0, 9):
  string.append(\"Hello\")

This way, you would have 9 \"Hello\" and you could get them individually like this:

string[x]

Where x would identify which \"Hello\" you want.

So, print(string[1]) would print Hello.