【问题标题】:How to make exception for a number in the range of for loop in python如何对python中for循环范围内的数字进行例外处理
【发布时间】:2015-08-13 00:18:14
【问题描述】:

在 Python 中,当我为变量定义范围时,例如

for i in range(0,9):

但在这里我想阻止i7 的值。我该怎么做?

【问题讨论】:

标签: python python-2.7 for-loop


【解决方案1】:

取决于你到底想做什么。如果您只想创建一个列表,您可以简单地执行以下操作:

ignore=[2,7] #list of indices to be ignored
l = [ind for ind in xrange(9) if ind not in ignore]

产生

[0, 1, 3, 4, 5, 6, 8]

您也可以直接在 for 循环中使用这些创建的索引,例如像这样:

[ind**2 for ind in xrange(9) if ind not in ignore]

给你

[0, 1, 9, 16, 25, 36, 64]

或者你应用一个函数

def someFunc(value):
    return value**3

[someFunc(ind) for ind in xrange(9) if ind not in ignore]

产生

[0, 1, 27, 64, 125, 216, 512]

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2016-11-08
    • 2019-03-17
    • 2013-07-15
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多