在python中跳过范围函数中的值
通过一系列数字循环并跳过一个值的Python方式是什么?例如,范围从0到100,我想跳过50 编辑: 这是我正在使用的代码在python中跳过范围函数中的值,python,loops,for-loop,range,Python,Loops,For Loop,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#) ... 这取决于你想做什么。例如,你可以在你的理解中加入如下条件: # get the squares of each number from
for i in range(0, len(list)):
x= listRow(list, i)
for j in range (#0 to len(list) not including x#)
...
这取决于你想做什么。例如,你可以在你的理解中加入如下条件:
# 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
你可以做的是,在循环中所有你想远离50的东西周围放一个if语句。 e、 g
除了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))
,即使它可以工作,因为它会将iterables扩展为一个元组,这是内存效率低下的
信贷:njzk2的评论,骆家辉的回答这对我来说很有效
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')
输出-->
带有条件的
continue
语句?我可以这样做,但是有没有办法将其放入循环本身的结构中?您在循环中做什么?第三个建议抛出TypeError,因为您没有显式创建迭代器(1)创建两个列表,(2)连接两个列表,(3)不起作用,xrange不是迭代器。(4) 应该使用xrange来避免创建列表,这是目前为止最好的解决方案。(1)如何创建两个列表<代码>xrange(100)不是列表。您可以通过返回一个生成器来避免创建第二个列表:为i in(x为x,x为x,x为x范围(100),如果x不是50)
#2使用Python 3.x:…list(范围(50))+list(范围(51100)):
@acumens这个问题被标记为Python
,而不是python3
。如果您有更高效的解决方案,请与他人分享,以便每个人都能受益:)
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