在循环中如何创建不同的变量名?[重复]

问题:在循环中如何创建不同的变量名?[重复]

出于示例目的…

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

所以我最终得到了string1,string2,string3 …都等于“ Hello”

For example purposes…

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

So I end up with string1, string2, string3… all equaling “Hello”


回答 0

你当然可以; 它被称为字典

d = {}
for x in range(1, 10):
    d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
 'string2': 'Hello',
 'string3': 'Hello',
 'string4': 'Hello',
 'string5': 'Hello',
 'string6': 'Hello',
 'string7': 'Hello',
 'string8': 'Hello',
 'string9': 'Hello'}

我说的有点难以理解,但实际上将一个值与另一个值相关联的最佳方法是字典。这就是它的设计目的!

Sure you can; it’s called a dictionary:

d = {}
for x in range(1, 10):
    d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'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!


回答 1

这真是个坏主意,但是…

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

然后例如:

print(string3)

会给你:

Hello

但是,这是不好的做法。如其他人建议的那样,您应该改用字典或列表。当然,除非您真的想知道如何做,但不想使用它。

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.


回答 2

一种方法是使用exec()。例如:

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

在这里,我利用了Python 3.6+中方便的f字符串格式

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+


回答 3

创建变量变量名根本没有意义。为什么?

  • 它们是不必要的:您可以将所有内容存储在列表,字典等中
  • 它们很难创建:您必须使用execglobals()
  • 您不能使用它们:如何编写使用这些变量的代码?您必须exec/globals()再次使用

使用列表要容易得多:

# 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

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

不要使用字典

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

不要使用字典

globals()存在风险,因为它会给您提供当前命名空间指向的内容,但是这可能会发生变化,因此修改globals()的返回值不是一个好主意

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

for x in range(9):
    exec("string" + str(x) + " = 'hello'")

这应该工作。

for x in range(9):
    exec("string" + str(x) + " = 'hello'")

This should work.


回答 6

我会使用一个列表:

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

这样,您将拥有9个“ Hello”,并且可以像这样单独获取它们:

string[x]

哪里 x可以找到您想要的“ Hello”。

因此,print(string[1])将打印Hello

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.


回答 7

我认为这里的挑战不是要调用global()

我将为要保存的(动态)变量定义一个列表,然后将其附加到for循环中。然后使用单独的for循环查看每个条目,甚至执行其他操作。

这是一个示例-我在不同的分支机构都有许多网络交换机(例如2到8之间)。现在,我需要确保有一种方法可以确定在任何给定分支上有多少个可用交换机(或活动ping测试),然后对它们执行一些操作。

这是我的代码:

import requests
import sys

def switch_name(branchNum):
    # s is an empty list to start with
    s = []
    #this FOR loop is purely for creating and storing the dynamic variable names in s
    for x in range(1,8,+1):
        s.append("BR" + str(branchNum) + "SW0" + str(x))

    #this FOR loop is used to read each of the switch in list s and perform operations on
    for i in s:
        print(i,"\n")
        # other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.


def main():  

    # for example's sake - hard coding the site code
    branchNum= "123"
    switch_name(branchNum)


if __name__ == '__main__':
    main()

输出为:

BR123SW01

BR123SW02

BR123SW03

BR123SW04

BR123SW05

BR123SW06

BR123SW07

I think the challenge here is not to call upon global()

I would personally define a list for your (dynamic) variables to be held and then append to it within a for loop. Then use a separate for loop to view each entry or even execute other operations.

Here is an example – I have a number of network switches (say between 2 and 8) at various BRanches. Now I need to ensure I have a way to determining how many switches are available (or alive – ping test) at any given branch and then perform some operations on them.

Here is my code:

import requests
import sys

def switch_name(branchNum):
    # s is an empty list to start with
    s = []
    #this FOR loop is purely for creating and storing the dynamic variable names in s
    for x in range(1,8,+1):
        s.append("BR" + str(branchNum) + "SW0" + str(x))

    #this FOR loop is used to read each of the switch in list s and perform operations on
    for i in s:
        print(i,"\n")
        # other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.


def main():  

    # for example's sake - hard coding the site code
    branchNum= "123"
    switch_name(branchNum)


if __name__ == '__main__':
    main()

Output is:

BR123SW01

BR123SW02

BR123SW03

BR123SW04

BR123SW05

BR123SW06

BR123SW07


回答 8

使用字典应该是保留变量和关联值的正确方法,您可以使用以下方法:

dict_ = {}
for i in range(9):
     dict_['string%s' % i]  = 'Hello'

但是,如果要将变量添加到局部变量中,可以使用:

for i in range(9):
     exec('string%s = Hello' % i)

例如,如果要为它们分配值0到8,则可以使用:

for i in range(9):
     exec('string%s = %s' % (i,i))

Using dictionaries should be right way to keep the variables and associated values, and you may use this:

dict_ = {}
for i in range(9):
     dict_['string%s' % i]  = 'Hello'

But if you want to add the variables to the local variables you can use:

for i in range(9):
     exec('string%s = Hello' % i)

And for example if you want to assign values 0 to 8 to them, you may use:

for i in range(9):
     exec('string%s = %s' % (i,i))

回答 9

字典可以包含值,并且可以使用update()方法添加值。您希望系统创建变量,因此您应该知道保留位置。

variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = variable
i = 0 
name = name + str(i) #this will be your variable name.
while True:
    value = 10 #value to assign
    variables.update(
                  {name:value})
    if break_condition == True:
        break

Dictionary can contain values and values can be added by using update() method. You want your system to create variables, so you should know where to keep.

variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = “variable”
i = 0 
name = name + str(i) #this will be your variable name.
while True:
    value = 10 #value to assign
    variables.update(
                  {name:value})
    if break_condition == True:
        break