【发布时间】:2015-08-13 00:18:14
【问题描述】:
在 Python 中,当我为变量定义范围时,例如
for i in range(0,9):
但在这里我想阻止i 取7 的值。我该怎么做?
【问题讨论】:
标签: python python-2.7 for-loop
在 Python 中,当我为变量定义范围时,例如
for i in range(0,9):
但在这里我想阻止i 取7 的值。我该怎么做?
【问题讨论】:
标签: python python-2.7 for-loop
取决于你到底想做什么。如果您只想创建一个列表,您可以简单地执行以下操作:
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]
【讨论】: