Python 查找列表中的每个第n个元素

Python 查找列表中的每个第n个元素,python,Python,如何查找列表的每个第n个元素 对于列表[1,2,3,4,5,6],returnNth(l,2)应该返回[1,3,5],对于列表[“狗”,“猫”,3,“仓鼠”,真],returnNth(u,2)应该返回[“狗”,3,真]。我该怎么做?您只需要lst[::n] 例如: >>> lst=[1,2,3,4,5,6,7,8,9,10] >>> lst[::3] [1, 4, 7, 10] >>> 我需要第n个元素 def returnNth(l

如何查找列表的每个第n个元素


对于列表
[1,2,3,4,5,6]
returnNth(l,2)
应该返回
[1,3,5]
,对于列表
[“狗”,“猫”,3,“仓鼠”,真]
returnNth(u,2)
应该返回
[“狗”,3,真]
。我该怎么做?

您只需要
lst[::n]

例如:

>>> lst=[1,2,3,4,5,6,7,8,9,10]
>>> lst[::3]
[1, 4, 7, 10]
>>> 

我需要第n个元素

  def returnNth(lst, n):
        # 'list ==> list, return every nth element in lst for n > 0'
        return lst[::n]

在python2.3中引入了its;请参阅文档了解-->可能重复的-1;这并没有添加任何其他两个答案(10分钟前发布)尚未提供的新内容。如果我们想要[2,5,8]?@Cosmic
lst[1::3]
  def returnNth(lst, n):
        # 'list ==> list, return every nth element in lst for n > 0'
        return lst[::n]