循环一系列数字并跳过一个值的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#)
...
您可以使用其中任何一个:
# 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
除了 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 中是迭代器。
如果跳过值的索引已知,则无需比较每个数字:
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 的评论
for i in range(0, 101):
if i != 50:
do sth
else:
pass
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]
这对我有用;
示例:
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
如果您想跳过初始数字可能未知的连续数字,最好使用
while
循环。
# Loop through a range of numbers from 0 to 100 and skip over number 50 as well
# as the next 3 consecutive numbers (51, 52, 53). Additionally, skip over 11 to 14.
i = 0
initial_skip_num = (50, 11, )
while i < 100:
if i in initial_skip_num:
i += 4
print(i)
i += 1
输出:
0
1
...
9
10
15
16
...
48
49
54
55
...
如果要跳过的初始数字未知或需要跳过多个连续数字,这会很有帮助
您可以使用set.difference:
list(set.difference(
set(range(0, 32)),
set((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 20, 21))))
结果:
Out[37]: [11, 14, 16, 17, 18, 19, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
你可以做的就是在循环内的所有你想要远离 50 的内容周围放置一个 if 语句。 例如
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#)