跳过 python 中 range 函数中的值

在一个数字范围内循环并跳过一个值的 Python 方法是什么?例如,范围是从0到100,我想跳过50。

编辑: 这是我使用的代码

for i in range(0, len(list)):
x= listRow(list, i)
for j in range (#0 to len(list) not including x#)
...
173077 次浏览
for i in range(100):
if i == 50:
continue
dosomething

这取决于你想做什么。例如,你可以在你的理解中加入这样的条件句:

# get the squares of each number from 1 to 9, excluding 2
myList = [i**2 for i in range(10) if i != 2]
print(myList)


# --> [0, 1, 9, 16, 25, 36, 49, 64, 81]

你可以使用以下任何一种:

# Create a range that does not contain 50
for i in [x for x in xrange(100) if x != 50]:
print i


# Create 2 ranges [0,49] and [51, 100] (Python 2)
for i in range(50) + range(51, 100):
print i


# Create a iterator and skip 50
xr = iter(xrange(100))
for i in xr:
print i
if i == 49:
next(xr)


# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print i

你可以做的是,在循环中的所有内容上加上一个 if 语句这样你就可以远离50了。 例如:。

for i in range(0, len(list)):
if i != 50:
x= listRow(list, i)
for j in range (#0 to len(list) not including x#)

除了 Python 2方法之外,这里还有 Python 3的等价物:

# Create a range that does not contain 50
for i in [x for x in range(100) if x != 50]:
print(i)


# Create 2 ranges [0,49] and [51, 100]
from itertools import chain
concatenated = chain(range(50), range(51, 100))
for i in concatenated:
print(i)


# Create a iterator and skip 50
xr = iter(range(100))
for i in xr:
print(i)
if i == 49:
next(xr)


# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print(i)

范围是 Python2中的列表和 Python3中的迭代器。

比较每个数字的时间效率很低,不必要地导致线性复杂性。话虽如此,这种方法避免了任何不平等检查:

import itertools


m, n = 5, 10
for i in itertools.chain(range(m), range(m + 1, n)):
print(i)  # skips m = 5

顺便说一句,即使 (*range(m), *range(m + 1, n))可以工作,您也不会想要使用它,因为它会将迭代扩展为一个元组,这样会导致内存效率低下。


图片来源: njzk2评论,Locke 回答

for i in range(0, 101):
if i != 50:
do sth
else:
pass

这对我有用;

例如:

x = ['apple', 'orange', 'grape', 'lion', 'banana', 'watermelon', 'onion', 'cat',]


for xr in x:
if xr in 'onion':
print('onion is a vegetable')
continue
if (xr not in 'lion' and xr not in 'cat'):
print(xr, 'is a fruit')

产出->

apple is a fruit
orange is a fruit
grape is a fruit
banana is a fruit
watermelon is a fruit
onion is a vegetable