在 Python 中跳过迭代变量的 N 个值的最佳方法是什么?
- 作者: 旁观者5151
- 来源: 51数据库
- 2022-10-28
问题描述
在许多语言中,我们可以这样做:
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]
如你所见,这很恶心.
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
