在Python的range函数中跳过一个值

78 投票
11 回答
202060 浏览
提问于 2025-04-18 08:55

在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#)
        ...

11 个回答

1

你可以使用 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]
1
for i in range(0, 101):
    if i != 50:
        do sth
    else:
        pass

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

2

如果你知道要跳过的值的索引,就不需要一个个去比较每个数字了:

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的评论

13

除了这里提到的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中,范围(ranges)是列表,而在Python 3中,范围则变成了迭代器。

108

你可以使用这些中的任何一个:

# 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

撰写回答