Get array values ​​in python

I have arr1 values ​​like 25.26 and arr2 values ​​like A, B

It is always always that the number of values ​​in arr1 and arr2 is equal to

My question is what

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

it is not possible to get arr2 values ​​in one loop or write another loop just for this purpose. Basically, the idea is to display the values ​​of arr1 and arr2

+6
source share
5 answers

You must do this with the python enumerate function. This allows you to iterate over the 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 gives:

 25 A 26 B 
+4
source

You can use the zip () function:

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

zip() creates a tuple for each pair of items in collections, then you map to each other. If your "arrays" have different lengths, you can use map() :

 a = [1,3,4] b = [3,4] print map(None, a, b) [(1, 3), (3, 4), (4, None)] 
+7
source
 for i in (arr1, arr2): for j in i.split(","): print j 

Output Results:

 25 26 A B 

So:

 for i in ",".join((arr1, arr2)).split(","): print i 

Although I think this second version is slower, much less readable and difficult to develop what is happening. Therefore, I stick to the first solution, even if it has an extra loop

+1
source

You cannot do this in only one cycle, it is not possible. You will have to do each cycle individually. This is actually not the case. Unfortunately.

+1
source

I do not think it can be as elegant as you hope. You must separate both, then iterate over the size of one array (assuming the other has the same size).

0
source

Source: https://habr.com/ru/post/889603/


All Articles