2

I'm trying to define k variables looking like x1, x2, ...xn, where each is a list (each list has 5 elements). meaning:

something like this:

     for i in [1..100]:
              "x" + str(i) = [ i + 2, i + 3, i + 3, i + 2, i + 4] 
              print ""x" + str(i)", 'x' + str(i) 

    ideal  output:
              x1 = [3,4,4,3,5]
              x2 = ...
              x3
              x4 
               .
               .
               .
              x100 = 

I am getting 'invalid syntax' messages. I'm open to anything that can get me over this fairly simple hurdle.

4

2 回答 2

2

你想要的是一个列表列表。有了列表理解,那就是

lists = [[i+2, i+3, i+3, i+2, i+4] for i in range(1, 101)]

这等效于以下for循环:

lists = []
for i in range(1, 101):
    lists.append([i+2, i+3, i+3, i+2, i+4])

x1你会写而不是写lists[0]。如果你想对元素进行数学运算,

lists[3][2] - lists[6][3]

将是你写的而不是

x4[2] - x7[3]
于 2013-07-21T00:24:22.237 回答
0

您可以使用 aclass或 withglobalslocalsdict 来执行此操作,例如:

class foo: pass

setattr(foo, 'variable', 'value')

print foo.variable

另一个例子__dict__

 class bar:
    def add_var(self, variable, value):
        self.__dict__[variable] = value
bar = bar()
bar.add_var("variable", "value")
print bar.variable

一个例子globals

globals()['variable'] = "value"
print variable

locals

locals()['var'] = "value"
print var
于 2013-07-21T00:34:33.690 回答