简体   繁体   English

for循环中的python调用变量

[英]python call variable in for loop

Recently I learn about PHP and in PHP I can do this最近我学习了 PHP,在 PHP 中我可以做到这一点

$var_1 = "";
$var_2 = "something";
$var_3 = "";
for($i = 1; $i <= 3; $i++){
  if(${"var_". $i} = ""){
    // do something
  }else{
    // do something
  }
}

And I want to know can I implement this to the python ?我想知道我可以在 python 中实现这个吗? Thank you.谢谢你。

Yes, but yuck, it is a horrible practice.是的,但是糟糕,这是一种可怕的做法。 Use a list and iterate directly instead of indexes.使用列表并直接迭代而不是索引。 You can access an individual variable via var[ index ] if needed.如果需要,您可以通过var[ index ]访问单个变量。

items = ['', 'something', '']
for item in items:
    if item == '':
        print('do something1')
    else:
        print('do something2')

Output:输出:

do something1
do something2
do something1

You can use the globals() function in python to access variables by their names as a string reference .您可以使用 python 中的globals()函数通过变量名称作为字符串引用来访问变量。

Here is an example of what you want to do:这是您要执行的操作的示例:

var_1 = ""
var_2 = "something"
var_3 = ""
for i in range(1, 4):
    if globals()[f"var_{i}"] == "":
        # do something
    else:
        # do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM