python - 如何使用for进入python循环

标签 python

其他语言

for(i=0; i<10; i++){
    if(...){
        i = 4;
    }
}

循环会上升, 但在 python 中,它不起作用

for i in range(1, 11):
    if ...:
        i = 4

那么我可以用'for'进入一个循环吗?

最佳答案

一种可能是您想跳过项目。与遍历索引有关的所有事情都很丑陋,但这里有一种使用 while 循环来做到这一点的方法。

i = 1
while i < 11:
    if predicate(i):
        i = 4
    i += 1

最好直接遍历列表中你想处理的项目,跳过你不想处理的项目。

for item in some_list_of_items:
    if not predicate(item):
        continue
    do_something_with_item(item)

或者使用生成器表达式来过滤项目

for item in (item for item in some_list_of_items if predicate(item)):
    do_something_with_item(item)

关于python - 如何使用for进入python循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4290399/

相关文章:

python - 将列表列表和 "distributing"元素从另一个列表获取到子列表的 Pythonic 方法是什么?

python - 读取某些行编码错误的 csv 文件并向用户返回错误行

python - 在python中显示在小数范围内

python - True + True = 2. 优雅地执行 boolean 运算?

python - 正则表达式替换匹配项

python - 为什么tensorflow LSTM只采用隐藏大小作为输入?

python - Tornado 或 Django 与 CGI 一起工作?

python - python中的random.normalvariate()和random.gauss()有什么区别?

python - pd.cut 的最小人口规模

python - Django 测试 : AssertionError: The form 'form' was not used to render the response