[英]how to assign each element of array to different variable in python
The array size is vary depending on the user input数组大小因用户输入而异
for example with size of 3例如大小为 3
array = [1,3,7]
to get要得到
a = 1
b = 3
c = 7
Use enumerate to get both the number and the index at the same time.使用 enumerate 同时获取数字和索引。
array = [1,3,7]
for pos, num in enumerate(array):
print(pos,num)
This will give you a output like this:这会给你一个 output 像这样:
0 1
1 3
2 7
So now to access the number at index 0
, simply write,所以现在要访问
index 0
处的数字,只需编写,
for pos, num in enumerate(array):
if pos == 0:
print(num)
Which will give you this output:这会给你这个 output:
1
Hope this helps.希望这可以帮助。
if you have name of the variables than you can use this如果您有变量的名称,则可以使用它
(a,b,c) = array
You probably want a dict instead of separate variables.您可能想要一个 dict 而不是单独的变量。 For example
例如
variavle_dictionary = {}
for i in range(len(array)):
variavle_dictionary["key%s" %i] = array[i]
print(variavle_dictionary)
{'key0': 1, 'key1': 2, 'key2': 3,}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.