在许多语言中,我们可以这样做:
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 个值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
使用 python 解析非常大的 xml 文件时出现问题Troubles while parsing with python very large xml file(使用 python 解析非常大的 xml 文件时出现问题)
使用 Python 2 在 XML 中按属性查找所有节点Find all nodes by attribute in XML using Python 2(使用 Python 2 在 XML 中按属性查找所有节点)
Python - 如何解析 xml 响应并将元素值存储在变量中Python - How to parse xml response and store a elements value in a variable?(Python - 如何解析 xml 响应并将元素值存储在变量中?)
如何在 Python 中获取 XML 标记值How to get XML tag value in Python(如何在 Python 中获取 XML 标记值)
如何使用 ElementTree 正确解析 utf-8 xml?How to correctly parse utf-8 xml with ElementTree?(如何使用 ElementTree 正确解析 utf-8 xml?)
将 XML 从 URL 解析为 python 对象Parse XML from URL into python object(将 XML 从 URL 解析为 python 对象)