开发者

Referencing the ith element of each list in a 2d list

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?

开发者_C百科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]


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜