【问题标题】:Get the first elements of lists within a list in Python获取Python列表中列表的第一个元素
【发布时间】:2020-07-31 10:10:00
【问题描述】:

我有一个包含 21 个列表的列表,每个列表包含 10 个元素,我想获得一个新列表,其中包含 3 个元素的 21 个列表的第一个元素。

如果我有[[1,2],[3,4]] 并且我想获得[1,3] (or [[1],[3]])

我知道如何通过循环获得这个,但我想使用更紧凑的方式。

例如,在 python 中,我们可以使用a[:3] 来创建一个简单的列表,但无论如何可以使用a[:][:3] (like in MATLAB a(:,1:3)) 之类的东西来进入列表中的列表吗?

【问题讨论】:

  • [i[:3] for i in a]
  • 你能详细说明前面的3个元素的第一个元素吗?
  • 我知道如何通过循环获得这个,但我想使用更紧凑的方式。 为什么?列表理解怎么样,这算作循环吗?

标签: python


【解决方案1】:

试试:

# first 3 items of list in big list    
small_list = [l[:3] for l in big_list]

代码:

big_list = [[1,2,3,4,5,6,7,8,9,10],["a","b","c","d","e","f","g","h","i","j"],[10,20,30,40,50,60,70,80,90, 100]]

small_list = [l[:3] for l in big_list]

print (small_list)

输出:

[[1, 2, 3], ['a', 'b', 'c'], [10, 20, 30]]

【讨论】:

    【解决方案2】:

    原生 Python 无法为列表的每个子列表获取范围和元素。除了列表理解之外,您可以做的最接近的方法是使用map

    oldList = [[1,2,3,4,5,6,7,8,9,10],["a","b","c","d","e","f","g","h","i","j"],[10,20,30,40,50,60,70,80,90, 100]]
    newList = list(map(lambda l: l[:3], oldList))
    

    但是,您可以下载并导入 numpy 库,它的语法类似于 Matlab 的语法:

    import numpy as np
    
    oldList = np.array([[1,2,3,4,5,6,7,8,9,10],["a","b","c","d","e","f","g","h","i","j"],[10,20,30,40,50,60,70,80,90, 100]])
    newList = big_list[:,0:3]
    
    print(newList)
    

    这将返回:

    [['1' '2' '3']
     ['a' 'b' 'c']
     ['10' '20' '30']]
    

    【讨论】:

      猜你喜欢
      • 2016-12-31
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多