[Python] I want to create a variable name in the for statement, is there any way?

Asked 2 years ago, Updated 2 years ago, 16 views

connection_list = ['user','password','db']
account_list = ['1','2','3','4']

for i in range(0, 4):
    vars()[connection_list[0]+account_list[0]]=connection_list[0]
    print(connection_list[i])

If you do so, the variable is

user1, password1, db1
user2, password2, db2
user3, password3, db3
user4, password4, db4

I thought you'd make it like this It's just created with user, password, and db. Is there any way?

python

2022-09-22 19:57

4 Answers

It is difficult to use a variable with a number attached to the variable name itself. Usually, it's better to just create a list variable and approach it as an index of the numbers in the list.

user = [ '', '', '' ]
password = [ '', '', '' ]
db = [ '', '' ,'' ]

user[0], password[0], db[0] = 'me', 'myword', 'mydb'
user[1], password[1], db[1] = 'you', 'yourword', 'urdb'
user[2], password[2], db[2] = 'she', 'herword', 'herdb'

for i in range(3):
  print(user[i], password[i], db[i])


2022-09-22 19:57

You can do it like this

## global
for i in range(1,5):
    globals()['user{}'.format(i)] = []
    globals()['password{}'.format(i)] = []
    globals()['db{}'.format(i)] = []


2022-09-22 19:57

class Example(object):
    pass


if __name__ == '__main__':
    connection_list = ['user', 'password', 'db']
    ex = Example()
    for cnt, x in enumerate(connection_list):
        setattr(ex, x+str(cnt), connection_list[0])
        print('{} => {}'.format(x+str(cnt), getattr(ex, x+str(cnt))))

This is also possible.


2022-09-22 19:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.