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
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;'
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.