Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop multiple variables in python

Tags:

python

loops

Say I have a thousand variables. v1,v2,v3,...,v1000, but they are just variables not in a list.

Is there any way I can loop them.

I know in c I can use Marcos.

But how can I do it in python? Any hints will be helpful.

like image 966
AlexWei Avatar asked Dec 01 '25 08:12

AlexWei


1 Answers

Alternative way is to use vars(). for example:

v1='dd';
v2=32;
v4=12;


import re
re_p = re.compile('^v\d+')

var_list = vars().copy()

for a_var in (v for v in var_list if re_p.match(v)):
    print(a_var, var_list[a_var])

Prints:

v1 dd
v4 12
v2 32
like image 89
Marcin Avatar answered Dec 03 '25 23:12

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!