1

please help me in parsing two-dimensional array. For example i have array :

arr = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3']]

and have loop, in them was creating the string with new one array and this one two-demensional array.

ex :

date = ['1 -', '2 -', '3 -']
string = ""
for i in range(len(date)):
   string = string + str(date[i]) + ...

how in this loop i can take string value like :

1 - a1,b1; 2 - a2,b2; 3 - a3,b3;

Thanks for the help

1 Answer 1

4

You can do something like thos:

>>> ' '.join('{} {};'.format(a, ','.join(b)) for a, b in zip(date, zip(*arr)))
'1 - a1,b1; 2 - a2,b2; 3 - a3,b3;'

Here first we transpose arr using zip with *:

>>> x = zip(*arr)
>>> x
[('a1', 'b1'), ('a2', 'b2'), ('a3', 'b3')]

Now we can zip this with date to get:

>>> y = zip(date, x)
>>> y
[('1 -', ('a1', 'b1')), ('2 -', ('a2', 'b2')), ('3 -', ('a3', 'b3'))]

Now we can simply loop through this array and perform string formatting and str.join operation on the items to get:

>>> z = ['{} {};'.format(a, ','.join(b)) for a, b in y]
>>> z
['1 - a1,b1;', '2 - a2,b2;', '3 - a3,b3;']

Now all we need to do is join these items using a ' ':

>>> ' '.join(z)
'1 - a1,b1; 2 - a2,b2; 3 - a3,b3;'
Sign up to request clarification or add additional context in comments.

2 Comments

thanks it's working, but question, if i have not two, but few array's in "arr", and them was change every time.
exaple, when i put in script other date i have : arr = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3'],['c1', 'c2', 'c3']]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.