我想使a1 = 0,a2 = 0,... aN = 0。 我以为使用“用于”
例如N = 10
required
但它不是零(仅打印)。 因此,我做了'a%d'%i = 0。但这没用
我该怎么做?
答案 0 :(得分:1)
您可以为此使用字典。
var_name = 'a'
for i in range(0, 10):
key = var_name + str(i) # an
new_values[key] = 0 # assign 0 to the new name
要单独访问它们,
new_values['a1']
>>> 0
或者您可以像这样一起访问它们,
for k,v in new_values.items():
print(k,'=',v)
输出:
a0 = 0
a1 = 0
a2 = 0
a3 = 0
a4 = 0
a5 = 0
a6 = 0
a7 = 0
a8 = 0
a9 = 0
答案 1 :(得分:1)
使用const值x=0
和计数器i
的简单解决方案:
x = 0
for i in range(0,10):
print(f"a{i} = {x}")
输出:
a0 = 0
a1 = 0
a2 = 0
a3 = 0
a4 = 0
a5 = 0
a6 = 0
a7 = 0
a8 = 0
a9 = 0
答案 2 :(得分:1)
对于打印,请使用.format()
(or f-strings on python 3.6+:
for i in range(0, 10):
print('a{} = {}'.format(i,i)) # the 1st i is put into the 1. {}, the 2nd i is put ...
如果要使用这些作为名称进行计算,请将它们存储在dictionary中,并使用值进行计算:
d = {}
for i in range(0, 10):
d["a{}".format(i)] = i # the nth i is put instead nth {}
print("sum a4 to a7: {} + {} + {} + {} = {}".format( # use the values stored in dict to
d["a4"], ["a5"], ["a6"], ["a7"], # calculate and print the single
d["a4"]+d["a5"]+d["a6"]+d["a7"])) # values where needed
输出:
# for loop
a0 = 0
a1 = 1
a2 = 2
a3 = 3
a4 = 4
a5 = 5
a6 = 6
a7 = 7
a8 = 8
a9 = 9
# calculation
sum a4 to a7: 4 + ['a5'] + ['a6'] + ['a7'] = 22
答案 3 :(得分:0)
In [1269]: for i in range(0, 10):
...: globals()['a'+ str(i)] = 0
...:
In [1270]: a1
Out[1270]: 0
In [1271]: a2
Out[1271]: 0
In [1272]: a3
Out[1272]: 0
In [1273]: a4
Out[1273]: 0
In [1274]: a5
Out[1274]: 0
In [1275]: a6
Out[1275]: 0
In [1276]: a7
Out[1276]: 0
In [1277]: a8
Out[1277]: 0
In [1278]: a9
Out[1278]: 0