在python中,如何使一组变量都等于相同的数字?

在python中,如何使一组变量都等于相同的数字?,python,Python,我正试着打印这样一块板 board = [ [a1, a2, a3, a4, a5, a6, a7, a8, a9], [b1, b2, b3, b4, b5, b6, b7, b8, b9], [c1, c2, c3, c4, c5, c6, c7, c8, c9], [d1, d2, d3, d4, d5, d6, d7, d8, d9], [e1, e2, e3, e4, e5, e6, e7, e8, e9], [f1, f2, f3, f4,

我正试着打印这样一块板

   board = [
   [a1, a2, a3, a4, a5, a6, a7, a8, a9],
   [b1, b2, b3, b4, b5, b6, b7, b8, b9],
   [c1, c2, c3, c4, c5, c6, c7, c8, c9],
   [d1, d2, d3, d4, d5, d6, d7, d8, d9],
   [e1, e2, e3, e4, e5, e6, e7, e8, e9],
   [f1, f2, f3, f4, f5, f6, f7, f8, f9],
   [g1, g2, g3, g4, g5, g6, g7, g8, g9],
   [h1, h2, h3, h4, h5, h6, h7, h8, h9],
   [i1, i2, i3, i4, i5, i6, i7, i8, i9]
   ]
但我必须给每个变量命名并将其等于零

   a1 = 0 a2 = 0 a3 = 0 a4 = 0 a5 = 0 a6 = 0 a7 = 0 a8 = 0 a9 = 0 b1 = 0
等等,一直到i9 这显然是令人讨厌的,我怎样才能在不改变电路板的情况下使它变小呢。 我不想打印新的电路板,只是简单地使变量a1-9到i1-9更紧凑

你觉得这样行吗

 myArray = a1=a2=a3=a4=a5=a6=a7=a8=a9=b1=b2=b3=[0]

您应该使用列表来完成该操作和循环

a=[0]*9
b=[0]*9
.
.
.
实际上,您可以创建一个列表,并将其全部放在一个易于访问的变量中

myList=[[0]*9表示范围(9)]

您可以创建一个二维列表,其中行表示字符(
'a'-'i'
),列表示数字(
1-9



您可以使用
矩阵[i][j]
对它们进行索引您可以使用字典:

data = {}
for i in range(10):
    for letter in list('abcdefghi'):
        data.update({letter+str(i):0})
输出:


我真的不鼓励使用这样的东西,即使它在Python3中似乎可以工作

for c in 'abcdefghi':
    for i in range(1,10):
        locals()[c+str(i)] = 0

print(a1,a3,i9)
打印:0 0 0

您可以使用string.ascii_小写生成从a到i的序列

from collections import defaultdict
import string

variables = defaultdict(int)
for value in string.ascii_lowercase[0:9]:
    for i in range(10):
        variables[value + str(i)]

print(variables)


对于如此多的变量,您可能希望使用数组或列表。但是,如果变量出于任何原因已经存在,您可能仍然希望将它们添加到数组中

myArray = [a1, a2, a3, a4,..., i9] #There is no shortcut. You have to hardcode them.
{element = 0 for element in myArray}
#Taking advantage of list comprehensions to do the work.
第二行与此不同:

myArray = [0 for element in myArray]
第一种方法更改数组中的变量(按引用传递),而第二种方法创建一个新的数组,其中包含相同数量的元素。如果使用对象(类)而不是基本数据类型,则此更改是有意义的。在您的示例中,这些是整数,因此这不适用。(这意味着两种方法都可以)

将变量添加到数组中还可以让您在将来做类似的工作


我敢肯定,这里的每个人都会建议首先使用数组并向其附加值,可能是一个循环,而不是为所有这些声明变量

尽管Ch3ster的答案更有意义,但如果您确实需要这样的变量,可以使用python的
globals()
函数。此函数返回作用域中每个变量的名称和值的字典,您可以这样修改它:

globals()[<the_name_of_the_new_variable]=<the_new_value>

letters="abcdefghi"
numbers="123456789"
for l in letters:
    for n in numbers:
        globals()[l+n]=0

这是一种肮脏的方法,但相当于为每个组合创建一个新变量。

a1=a2=a3..=0
?您需要这些变量做什么?你不应该使用列表吗?我想你应该使用字典,我建议你提供更多的细节,这样我们可以帮助你,不是吗?@Ch3steR是的,我的badUpvoting,因为你现在是有效的。也许值得补充的是,在Python中,与其他一些语言不同,你不能使用
a[I,j]
访问此类列表的元素,但是,
a[i][j]
。@Błotosmętek同意。添加它。你可以编辑我的答案,只要它有意义。
myArray = [a1, a2, a3, a4,..., i9] #There is no shortcut. You have to hardcode them.
{element = 0 for element in myArray}
#Taking advantage of list comprehensions to do the work.
myArray = [0 for element in myArray]
globals()[<the_name_of_the_new_variable]=<the_new_value>

letters="abcdefghi"
numbers="123456789"
for l in letters:
    for n in numbers:
        globals()[l+n]=0