简体   繁体   中英

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

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.

array = [1,3,7]
for pos, num in enumerate(array):
    print(pos,num)

This will give you a output like this:

0 1
1 3
2 7

So now to access the number at index 0 , simply write,

for pos, num in enumerate(array):
    if pos == 0:
        print(num)

Which will give you this 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. 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,}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM