Suppose I have a list of lists:
mylist = [
[2.1, 5.2, 6.1, -0.1],
[2.2, 4.8, 5.6, -1.0],
[3.3, 6.5, 5.9, 1.2],
[2.9, 5.6, 6.0, 0.0],
]
How do I get the second [1] and fourth [3] element using a list comprehension to get a new list? It should look like this:
result =[
[5.2, -0.1],
[4.8, -1.0],
[6.5, 1.2],
[5.6, 0.0]
]
CodePudding user response:
You can do this,
result = [[item[1],item[3]] for item in mylist]
print(result)
# [[5.2, -0.1], [4.8, -1.0], [6.5, 1.2], [5.6, 0.0]]
Just access the 1
and 3
elements and put them into another list.