Referencing the ith element of each list in a 2d list
Question
Take a 2d list. I want to make a new list with only the ith element from each list. What is the best way to do this?
I have:
map(lambda x: x[i], l)
Here is an example
>>> i = 0
>>> l = [[1,10],[2,20],[3,30]]
>>> map(lambda x: x[i], l)
[1, 2, 3]
Solution
Use list comprehension:
i = 1
data = [[1,10],[2,20],[3,30]]
result = [d[i] for d in data] # [10, 20, 30]
Also see this question on list comprehension vs. map.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow