Python 查找列表中的每个第 n 个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14680273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding every nth element in a list
提问by iKyriaki
How can I find every nth element of a list?
如何找到列表的每个第 n 个元素?
For a list [1,2,3,4,5,6], returnNth(l,2)should return [1,3,5]and for a list ["dog", "cat", 3, "hamster", True], returnNth(u,2)should return ['dog', 3, True]. How can I do this?
对于列表[1,2,3,4,5,6],returnNth(l,2)应该返回[1,3,5],对于列表["dog", "cat", 3, "hamster", True],returnNth(u,2)应该返回['dog', 3, True]。我怎样才能做到这一点?
采纳答案by us2012
You just need lst[::n].
你只需要lst[::n].
Example:
例子:
>>> lst=[1,2,3,4,5,6,7,8,9,10]
>>> lst[::3]
[1, 4, 7, 10]
>>>
回答by avasal
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]
回答by sufinsha
I you need the every nth element....
我需要每个第 n 个元素....
def returnNth(lst, n):
# 'list ==> list, return every nth element in lst for n > 0'
return lst[::n]

