【问题标题】:Referencing the ith element of each list in a 2d list引用二维列表中每个列表的第 i 个元素
【发布时间】:2011-05-05 08:21:28
【问题描述】:

获取二维列表。 我想用每个列表中的第 i 个元素创建一个新列表。 最好的方法是什么?

我有:

 map(lambda x: x[i], l)

这是一个例子

 >>> i = 0
 >>> l = [[1,10],[2,20],[3,30]]
 >>> map(lambda x: x[i], l)
 [1, 2, 3]

【问题讨论】:

    标签: python map subscript


    【解决方案1】:

    使用list comprehension:

    i = 1
    data = [[1,10],[2,20],[3,30]]
    result = [d[i] for d in data]  # [10, 20, 30]
    

    也可以在 list comprehension vs. map 上查看这个问题。

    【讨论】:

    • 或适应原始问题result = [x[i] for x in l]
    • 仅供参考,列表理解比地图更高度优化。
    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 2015-07-15
    • 2020-09-20
    • 2015-02-12
    • 2021-10-28
    • 2015-08-18
    • 2021-08-22
    相关资源
    最近更新 更多