Reputation: 13
I have this list
[[['21832', '1524', '30', '133'], ['16142', '1233', '17', '113']],
[['23296', '1570', '34', '138'], ['17243', '1277', '18', '118']],
[['23296', '1570', '34', '138'], ['17243', '1278', '18', '118']],
[['25919', '1658', '35', '141'], ['19081', '1344', '21', '124']]]
And I want to create new list like,
[21832,23296,23296,25919]
[1524,1570,1570,1658]
[30,34,34,35]
How can I do?
Upvotes: 1
Views: 66
Reputation: 991
All great answers! I have to throw in a list comprehension solution...
test_lists = [[['21832', '1524', '30', '133'], ['16142', '1233', '17', '113']],
[['23296', '1570', '34', '138'], ['17243', '1277', '18', '118']],
[['23296', '1570', '34', '138'], ['17243', '1278', '18', '118']],
[['25919', '1658', '35', '141'], ['19081', '1344', '21', '124']]]
first_lists = [first_list[0] for first_list in test_lists]
firsts_list = [elements[0] for elements in first_lists]
seconds_list = [elements[1] for elements in first_lists]
thirds_list = [elements[2] for elements in first_lists]
fourths_list = [elements[3] for elements in first_lists]
# firsts_list: ['21832', '23296', '23296', '25919']
# seconds_list: ['1524', '1570', '1570', '1658']
# thirds_list: ['30', '34', '34', '35']
# fourths_list: ['133', '138', '138', '141']
Upvotes: 0
Reputation: 164693
If you are happy using a 3rd party library, you can use numpy
:
import numpy as np
lst = [[['21832', '1524', '30', '133'], ['16142', '1233', '17', '113']],
[['23296', '1570', '34', '138'], ['17243', '1277', '18', '118']],
[['23296', '1570', '34', '138'], ['17243', '1278', '18', '118']],
[['25919', '1658', '35', '141'], ['19081', '1344', '21', '124']]]
res = np.array(lst)[:,0,:3].T
Result:
array([['21832', '23296', '23296', '25919'],
['1524', '1570', '1570', '1658'],
['30', '34', '34', '35']],
dtype='<U11')
Upvotes: 1
Reputation: 71451
You can use zip
with unpacking:
d = [[['21832', '1524', '30', '133'], ['16142', '1233', '17', '113']],
[['23296', '1570', '34', '138'], ['17243', '1277', '18', '118']],
[['23296', '1570', '34', '138'], ['17243', '1278', '18', '118']],
[['25919', '1658', '35', '141'], ['19081', '1344', '21', '124']]]
new_d = list(map(list, zip(*[list(map(int, a)) for [*a, b], _ in d])))
Output:
[[21832, 23296, 23296, 25919], [1524, 1570, 1570, 1658], [30, 34, 34, 35]]
Upvotes: 1