Concatenating variable names in Python [duplicate]

ⅰ亾dé卋堺 提交于 2020-01-06 02:07:02

问题


I need to check variables looking like this:

if name1 != "":
    (do something)

Where the number right after "name" is incremented between 1 and 10.

Do I need to write the test ten times or is there a way (without using an array or a dict) to "concatenate", so to speak, variable names?

I'm thinking about something like this:

for i in range(10):
    if "name" + str(i) != "":
        (do something)

Edit: I can't use a list because I'm actually trying to parse results from a Flask WTF form, where results are retrieved like this:

print(form.name1.data)
print(form.name2.data)
print(form.name3.data)
etc.

回答1:


  1. Use a list, such as:

    names = ['bob', 'alice', 'john']
    

    And then iterate on the list:

    for n in names:
      if n != "":
         (do something)
    
  2. or you could have a compounded if statement:

    if (name1 != "" or name2 != "" or name3 != "")
    

The best solution would be to use solution #1.




回答2:


If you cannot use a list or a dict, you could use eval

for i in range(10):
    if eval("name" + str(i)) != "":
        (do something)



回答3:


First of all, your app have invalid logic. You should use list, dict or your custom obj.

You can get all variable in globals. Globals is a dict.

You can do next:

for i in range(10):
    if globals().get('name%d' % i):
        # do something


来源:https://stackoverflow.com/questions/36898891/concatenating-variable-names-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!