在Python中,当我为变量定义范围时,例如
for i in range(0,9):
但是这里我想阻止i
取7
的值。我该怎么做呢?
这取决于你到底想做什么。如果你只想创建一个列表,你可以这样做:
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]