如何在python上执行while循环定义x1,x2,x3等

时间:2015-12-02 16:23:25

标签: python for-loop while-loop

你好我需要在python中定义一系列数据,比如(x1 = thing,x2 = thing ... to x100 = thing),我不想写所有的x(数字)。我尝试了这样的循环

a=1
while(a<100):
    x'a'=thing
    a=a+1

但这不起作用...... 我如何做一个循环让我这样:

x1=thing
x2=thing
x3=thing
x4=thing
etc...  

我不需要打印它,只需定义de x(数字)。 谢谢人们

2 个答案:

答案 0 :(得分:0)

你没有。这并不是说你不能,但你绝对不想。

foo = []
for _ in range(100):  # do the following 100 times:
    foo.append("thing")
# or foo = ['thing' for _ in range(100)]
# or foo = ['thing'] * 100

这将为您提供一个名为list的{​​{1}},其值为foo,位于0到99之间的每个元素中。

"thing"

另一种方法是直接操纵foo[0] # "thing" foo[99] # "thing" foo[100] # throws an IndexError 字典(这是一个坏主意)或使用globals(这是一个非常糟糕的主意)。

exec

for num in range(1, 101):
    exec("x{} = 'thing'".format(num))
    # oh my God don't do this

这并不是说for num in range(1, 101): globals()["x{}".format(num)] = "thing" # it's so ugly it burns! 天生就是坏事,也不是直接操纵exec字典就没有它的位置。但是,如果您正处于教育阶段,您仍然在StackOverflow上询问有关Python的问题,那么您甚至不应该 考虑使用这些方法 。充其量它是一个丑陋的黑客,你应该做其他事情。在最坏的情况下,它会破坏您的脚本并允许恶意(或不知情的......读取:您自己)用户在您的计算机上做任何想做的事情。这包括:

globals

答案 1 :(得分:0)

谢谢大家!事实证明我并没有完全知道如何使用列表哈哈哈...这最终对我有用:

lina=[0,0]
linb=[0,0]
fig=plt.figure()
a=1
while(a<2):
   lina[a],=fig.add_subplot(111).plot(x,x, 'b^',markersize=20)
   linb[a],=fig.add_subplot(111).plot(x,x, 'rv',markersize=20)    
   a=a+1