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 个值的最佳方法是什
基础教程推荐
猜你喜欢
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
