【问题标题】:Python return list from nth element from sublistPython 从子列表的第 n 个元素返回列表
【发布时间】:2023-01-10 00:30:32
【问题描述】:

有没有办法: 从列表开始 lst=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

我想要一个新列表,其中包含子列表中的每一秒(第 n 个)元素 新列表:[2,5,8,11]

和或 来自 lst[1:3] 的每隔一个(第 n 个)元素的新列表 新列表:[5,8]

提前致谢

【问题讨论】:

标签: python list


【解决方案1】:

要从整个列表中每隔一个元素创建一个新列表,您可以执行以下操作: new_list = [lst[i][1] for i in range(len(lst))]

【讨论】:

  • 为什么不只是[sublist[1] for sublist in lst]
【解决方案2】:

如果这是一个重复操作,您可能希望将其变成一个可重用的函数。随意删除类型注释。

def get_nth_elements(list_of_lists: List[List[Any]], n: int) -> List[Any]:
   """Get the nth element from each list in a given list of lists"""
   return [sub_list[n] for sub_list in list_of_lists]

【讨论】:

    【解决方案3】:

    谢谢约翰 lst2=[sublist[1] for sublist in lst[1:3]] 是我要找的

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 2014-12-20
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-12
      • 1970-01-01
      • 2018-05-27
      相关资源
      最近更新 更多