简体   繁体   English

如何将数组的每个元素分配给 python 中的不同变量

[英]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.

相关问题 在 Python 中为数组的每个元素分配一个标签 - Assign a label to each element of an array in Python 如何将列表的每个元素分配给一个单独的变量? - How to assign each element of a list to a separate variable? 如何为numpy数组变量中的每一行制作不同的元素? - How to make different element for each row in numpy array variable? 如何在python中为列表的每个元素指定一个名称 - How to assign a name to each element of a list in python 如何为numpy向量的每个元素分配大小不同的3d numpy数组? - How do I assign a 3d numpy array of different sizes to each element of a numpy vector? Python:如何将列表或数组分配给数组元素? - Python:How to assign a list or an array to an array element? 如何循环和索引 python 中的文件内容并将每一行分配给不同的变量 - How to loop and index through file content in python and assign each line for different variable Python数组变量分配 - Python Array Variable Assign 如何将不同的变量归因于列表的每个元素 - How to attribut a different variable to each element of list 如何在不更改 python 中的原始值的情况下将二维数组中的元素分配给新变量? - How to assign an element from a 2D array to a new variable without changing its original value in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM