Finding every nth element in a list

后端 未结 3 905
滥情空心
滥情空心 2020-12-16 05:31

How can I find every nth element of a list?

For a list [1,2,3,4,5,6], returnNth(l,2) should return [1,3,5] and for a list

相关标签:
3条回答
  • 2020-12-16 05:46

    I you need the every nth element....

      def returnNth(lst, n):
            # 'list ==> list, return every nth element in lst for n > 0'
            return lst[::n]
    
    0 讨论(0)
  • 2020-12-16 05:50

    You just need lst[::n].

    Example:

    >>> lst=[1,2,3,4,5,6,7,8,9,10]
    >>> lst[::3]
    [1, 4, 7, 10]
    >>> 
    
    0 讨论(0)
  • 2020-12-16 05:57
    In [119]: def returnNth(lst, n):
       .....:     return lst[::n]
       .....:
    
    In [120]: returnNth([1,2,3,4,5], 2)
    Out[120]: [1, 3, 5]
    
    In [121]: returnNth(["dog", "cat", 3, "hamster", True], 2)
    Out[121]: ['dog', 3, True]
    
    0 讨论(0)
提交回复
热议问题