bobdaves69
bobdaves69

Reputation: 79

Combining elements within a 2d array python 3.x

i have this 2d array, where each array is made up of 4 lots of 4 hex values:

list1=[['74 68 61 74', '73 20 6D 79', '20 6B 75 6E', '67 20 66 75'], ['C2 5B FC F1', 'B1 7B 91 88', '91 10 E4 E6', 'F6 30 82 93']]

And I would like to firstly split the array into multiple 1d arrays then combine the array into multiple single elements rather than each element having 4 values, like follows:

list2=[74, 68, 61, 74, 73, 20, 6D, 79, 20, 6B, 75, 6E, 67, 20, 66, 75]

list 3=[C2, 5B, FC, F1, B1, 7B, 91, 88, 91, 10, E4, E6, F6, 30, 82, 93]

Please let me know how this can be done. Thank you in advance.

Upvotes: 0

Views: 56

Answers (1)

AirSquid
AirSquid

Reputation: 11903

What you essentially want to do is "flatten" the inner lists. There are several approaches to this. The example below borrows from here. Realize that the values in your lists are just strings (even though they could represent hex values) so you need to treat them like strings when splitting them up.

In [25]: list1                                                                    
Out[25]: 
[['74 68 61 74', '73 20 6D 79', '20 6B 75 6E', '67 20 66 75'],
 ['C2 5B FC F1', 'B1 7B 91 88', '91 10 E4 E6', 'F6 30 82 93']]

In [26]: list2 = [t for sublist in list1[0] for t in sublist.split(' ')]          

In [27]: list3 = [t for sublist in list1[1] for t in sublist.split(' ')]          

In [28]: list2                                                                    
Out[28]: 
['74',
 '68',
 '61',
 '74',
 '73',
 '20',
 '6D',
 '79',
 '20',
 '6B',
 '75',
 '6E',
 '67',
 '20',
 '66',
 '75']

In [29]: list3                                                                    
Out[29]: 
['C2',
 '5B',
 'FC',
 'F1',
 'B1',
 '7B',
 '91',
 '88',
 '91',
 '10',
 'E4',
 'E6',
 'F6',
 '30',
 '82',
 '93']

In [30]:   

Upvotes: 1

Related Questions