python – 如何组合两个for循环

可以说我正在尝试打印0到25和75到100.

现在我有:

for x in range(0, 26):
    print(x)
for x in range(75, 101):
    print(x)

有没有办法将这些组合成一个for循环导致:

print(x)

有点像:

for x in range(0, 26) and range(75, 101):
    print(x)

最佳答案 你需要
itertools.chain()

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.

from itertools import chain

for x in chain(range(0, 26), range(75, 101)):
    print(x)

适用于Python 2和3.

点赞