Python String+Match Variables

Asked 2 years ago, Updated 2 years ago, 22 views

I want to add the variables to the string in the for statement, and then run the attributes that the object has. For example,

a1=[]
a2=[]
a3=[]
a4=[]
for i in range(0,5):
    'a%d'%i.append(i)

I want to do it with you Isn't there a good way?

python

2022-09-21 14:47

2 Answers

a = [[], [], [], [], []]

for i in range(5):
    a[i].append(i)

In this way, write a[0] and a[1] instead of a1 and a2.


2022-09-21 14:47

Try to learn reflection.

import sys
mod = sys.modules[__name__]
for n in range(1, 11):
    setattr(mod, 'list{}'.format(n), [])

for n in range(1, 11):
    getattr(mod, 'list{}'.format(n)).append(n)

print(list1)
print(list10)

[1]
[10]


2022-09-21 14:47

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.