【问题标题】:Make a list out of items in a sublist of a multidimensional list (python)用多维列表的子列表中的项目制作列表(python)
【发布时间】:2013-07-30 10:27:58
【问题描述】:

我的问题如下:

我有这个列表:[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 我想得到这个列表:[2, 5, 8]

这是列表列表中每个子列表的第二个元素 (index: 1)。 我怎么能在 Python 中做到这一点?

感谢您的宝贵时间。

【问题讨论】:

标签: python list multidimensional-array


【解决方案1】:

使用list comprehension

L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
M = [y for [x, y, z] in L]

【讨论】:

    【解决方案2】:

    只需使用列表推导:

    In [88]: l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    In [89]: [x[1] for x in l]
    Out[89]: [2, 5, 8]
    

    【讨论】:

    • 啊...看起来比我想象的要容易!非常感谢:)
    【解决方案3】:

    您可以使用list comprehension 进行操作,如下所示:

    l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    a = [x[1] for x in l]
    

    或者使用map:

    a = map(lambda x: x[1], l)
    

    或者使用mapoperator.itemgetter 而不是lambda,根据下面的评论:

    import operator
    a = map(operator.itemgetter(1), l)
    

    【讨论】:

    • operator.itemgetter 优于 lambda
    • @AshwiniChaudhary,感谢您的意见。我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-05-30
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多