Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get array values in python

Tags:

python

I have the values arr1 as 25,26 and arr2 values as A,B

Its always that the number of values in arr1 and arr2 are equal

My question is that

          for i in arr1.split(","):
                print i //prints 25 and 26

is it not possible to get the values of arr2 in the same loop or should another loop be written only for this purpose.Basically the idea is that map the values of arr1 and arr2

like image 612
Rajeev Avatar asked Jun 02 '11 07:06

Rajeev


People also ask

How do I get all the values of an array in Python?

Use the len() method to return the length of an array (the number of elements in an array).

How do you access values in an array?

As storing value in array is very simple, the accessing value from array is also so simple. You can access array's value by its index position. Each index position in array refers to a memory address in which your values are saved.


2 Answers

You can use zip() function:

for zipped in zip(arr1.split(",") , arr2.split(",")):
    someDictionary[zipped[0]] = zipped[1]

zip() creates tuple for each pair of items in collections, then you map one to another. If your 'arrays' have diffrent length, you can use map():

a = [1,3,4]
b = [3,4]
print map(None, a, b)
[(1, 3), (3, 4), (4, None)]
like image 175
Ilya Smagin Avatar answered Sep 24 '22 21:09

Ilya Smagin


You should be able to do this with python's enumerate function. This lets you loop through a list and get both its numerical index and its value:

array1 = arr1.split(',')
array2 = arr2.split(',')
for i,value in enumerate(array1):
   print value, array2[i]

This produces:

25 A
26 B
like image 32
Dave Challis Avatar answered Sep 21 '22 21:09

Dave Challis