在Python中串联变量名称 [英] Concatenating variable names in Python

查看:60
本文介绍了在Python中串联变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查变量,如下所示:

I need to check variables looking like this:

if name1 != "":
    (do something)

名称后面的数字在1到10之间递增。

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?

我在想像这样的东西:

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

编辑:我无法使用列表,因为我实际上是试图从Flask WTF表单中解析结果,在该表单中以如下方式检索结果:

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)


  • 拥有复合if语句:

  • or you could have a compounded if statement:

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


  • 最好的解决方案是使用解决方案# 1。

    The best solution would be to use solution #1.

    这篇关于在Python中串联变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆