I have two lists like
JavaScript
x
3
1
values = [['bert', '1234', 'xxx', 50], ['ernie', '5678', 'fff', 100]]
2
required = [1, 3]
3
I want to extract the required
elements 1 and 3 from each list contained in values
, to create a new list of lists like [['1234', 50], ['5678', 100]]
.
I was able to solve the problem with a list comprehension:
JavaScript
1
2
1
[[x[y] for y in required] for x in values]
2
But how can I write the equivalent with explicit for
loops?
I tried:
JavaScript
1
5
1
new_list = []
2
for x in values:
3
for y in required:
4
new_list.append(x[y])
5
but the resulting new_list
is a single flat list ['1234', 50, '5678', 100]
.
Advertisement
Answer
You can make a new array before second looping, and then add x[y] in that array. Add the new array to the new_list after the second looping.
JavaScript
1
7
1
new_list = []
2
for x in values:
3
temp_list = []
4
for y in required:
5
temp_list.append(x[y])
6
new_list.append(temp_list)
7