循环遍历一系列数字并跳过一个值的pythonic方法是什么?例如,范围从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#)
...
答案 0 :(得分:62)
您可以使用以下任何一种:
# 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
答案 1 :(得分:1)
for i in range(100):
if i == 50:
continue
dosomething
答案 2 :(得分:1)
这取决于你想做什么。例如,你可以在你的理解中坚持这样的条件:
# 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]
答案 3 :(得分:1)
除了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)
范围是Python 2中的列表和Python 3中的迭代器。
答案 4 :(得分:0)
比较每个数字很浪费时间,不必要地导致线性复杂性。话虽如此,这种方法避免了任何不平等检查:
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发表评论,洛克提供答案
答案 5 :(得分:0)
r
答案 6 :(得分:0)
这对我有用;
示例:
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
答案 7 :(得分:-1)
你可以做什么,在你想要远离50的循环中放置一个if语句。 e.g。
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#)