I have two lists like
values = [['bert', '1234', 'xxx', 50], ['ernie', '5678', 'fff', 100]]
required = [1, 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:
[[x[y] for y in required] for x in values]
But how can I write the equivalent with explicit for
loops?
I tried:
new_list = []
for x in values:
for y in required:
new_list.append(x[y])
but the resulting new_list
is a single flat list ['1234', 50, '5678', 100]
.
CodePudding user response:
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.
new_list = []
for x in values:
temp_list = []
for y in required:
temp_list.append(x[y])
new_list.append(temp_list)
CodePudding user response:
Using plain index (and list comprehension):
values = [['bert', '1234', 'xxx', 50], ['ernie', '5678', 'fff', 100]]
required = [1, 3]
output = [[sublst[i] for i in required] for sublst in values]
print(output) # [['1234', 50], ['5678', 100]]
Using operator.itemgetter
:
from operator import itemgetter
values = [['bert', '1234', 'xxx', 50], ['ernie', '5678', 'fff', 100]]
required = [1, 3]
output = [itemgetter(*required)(sublst) for sublst in values]
print(output) # [('1234', 50), ('5678', 100)]