Python 在不使用计数器变量的情况下每 n 次迭代做一些事情
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21879424/
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
Do something every n iterations without using counter variable
提问by PythonEnthusiast
I've an iterable list of over 100 elements. I want to do something after every 10th iterable element. I don't want to use a counter variable. I'm looking for some solution which does not includes a counter variable.
我有一个包含 100 多个元素的可迭代列表。我想在每 10 个可迭代元素之后做一些事情。我不想使用计数器变量。我正在寻找一些不包含计数器变量的解决方案。
Currently I do like this:
目前我喜欢这样:
count = 0
for i in range(0,len(mylist)):
if count == 10:
count = 0
#do something
print i
count += 1
Is there some way in which I can omit counter variable?
有什么方法可以省略计数器变量吗?
采纳答案by Jakob Bowyer
回答by Avinash Garg
for i in range(0,len(mylist)):
if (i+1)%10==0:
do something
print i
回答by Burhan Khalid
A different way to approach the problem is to split the iterable into your chunks before you start processing them.
解决该问题的另一种方法是在开始处理之前将可迭代对象拆分为多个块。
The grouperrecipedoes exactly this:
该grouper配方正是这样做的:
from itertools import izip_longest # needed for grouper
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
You would use it like this:
你会像这样使用它:
>>> i = [1,2,3,4,5,6,7,8]
>>> by_twos = list(grouper(i, 2))
>>> by_twos
[(1, 2), (3, 4), (5, 6), (7, 8)]
Now, simply loop over the by_twoslist.
现在,只需循环遍历by_twos列表即可。
回答by mdscruggs
Just to show another option...hopefully I understood your question correctly...slicing will give you exactly the elements of the list that you want without having to to loop through every element or keep any enumerations or counters. See Explain Python's slice notation.
只是为了显示另一个选项……希望我正确理解了您的问题……切片将为您提供所需的列表元素,而无需遍历每个元素或保留任何枚举或计数器。请参阅解释 Python 的切片符号。
If you want to start on the 1st elementand get every 10th element from that point:
如果您想从第1 个元素开始并从该点获取每 10 个元素:
# 1st element, 11th element, 21st element, etc. (index 0, index 10, index 20, etc.)
for e in myList[::10]:
<do something>
If you want to start on the 10th elementand get every 10th element from that point:
如果您想从第10 个元素开始并从该点获取每第 10 个元素:
# 10th element, 20th element, 30th element, etc. (index 9, index 19, index 29, etc.)
for e in myList[9::10]:
<do something>
Example of the 2nd option (Python 2):
第二个选项的示例(Python 2):
myList = range(1, 101) # list(range(1, 101)) for Python 3 if you need a list
for e in myList[9::10]:
print e # print(e) for Python 3
Prints:
印刷:
10
20
30
...etc...
100

