For循环输出到变量或Python中的列表

2024-04-26 13:32:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为Python中的变量分配for循环输出值。

onetoten = range(1,5)
for count in onetoten:
    print (count)

上述for循环的输出如下

1
2
3
4

我想把这个输出分配给一个变量列表,比如s1 = 1s2 = 2s3 =3s4 = 4。 但没有具体数字显示名单将持续到4日。它可能会根据脚本中以前的输出而有所不同。因此,根据for循环的输出,变量的数量也必须增加,或者根据输出的数量使用变量。请帮忙。

我之前问过同样的问题,在那里我得到了使用枚举的响应,但这并不完全是python,我在Jython中使用的是脚本,所以我在Jython中没有枚举。


Tags: in脚本列表for数量s3countrange
3条回答

您还可以使用python列表理解,并得到一个列表作为结果。

my_list = [x for x in range(1,5)]
print(my_list)

要获得此结果:

[1, 2, 3, 4]

你可以用索引访问它

print("my_list[0] is: {}".format(my_list[0]))

如果知道变量的数量,请使用序列解包:

>>> s1,s2,s3,s4 = range(1,5)
>>> s1
1
>>> s2
2
>>> s3
3
>>> s4
4

如果你说的是创建动态变量,那么这是个坏主意,我更喜欢dict

>>> dic = {}
>>> for x in range(1,5):
...     dic['s' + str(x)] = x
...     
>>> dic['s1']
1
>>> dic['s2']
2

可以使用globals()在python中创建动态变量,但不建议这样做:

>>> globals()['foo'] = 'bar'
>>> foo
'bar'

I want to assign this output to a list of variables like s1 = 1, s2 = 2, s3 =3 and s4 = 4. But there is no specific number that the list will be till 4. It may vary based on previous output in the script.

这意味着您确实不想使用多个变量。将值存储在序列s中。然后可以使用s[n-1],而不是sn

>>> s = range(1,5)
>>> s[0]
1
>>> s[1]
2
etc.

如果您需要更灵活的命名,即特定的标识符-值对,那么您应该考虑按照建议使用dict

相关问题 更多 >