What#39;s the best way of skip N values of the iteration variable in Python?(在 Python 中跳过迭代变量的 N 个值的最佳方法是什么?)
本文介绍了在 Python 中跳过迭代变量的 N 个值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在许多语言中,我们可以这样做:
In many languages we can do something like:
for (int i = 0; i < value; i++)
{
if (condition)
{
i += 10;
}
}
如何在 Python 中做同样的事情?以下(当然)不起作用:
How can I do the same in Python? The following (of course) does not work:
for i in xrange(value):
if condition:
i += 10
我可以这样做:
i = 0
while i < value:
if condition:
i += 10
i += 1
但我想知道在 Python 中是否有更优雅的 (pythonic?) 方法.
but I'm wondering if there is a more elegant (pythonic?) way of doing this in Python.
推荐答案
使用继续
.
for i in xrange(value):
if condition:
continue
如果你想强制你的迭代向前跳过,你必须调用 .next()
.
If you want to force your iterable to skip forwards, you must call .next()
.
>>> iterable = iter(xrange(100))
>>> for i in iterable:
... if i % 10 == 0:
... [iterable.next() for x in range(10)]
...
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
[61, 62, 63, 64, 65, 66, 67, 68, 69, 70]
[81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
如你所见,这很恶心.
这篇关于在 Python 中跳过迭代变量的 N 个值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在 Python 中跳过迭代变量的 N 个值的最佳方法是什


猜你喜欢
- 沿轴计算直方图 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01