连接两个范围函数结果 [英] Concatenating two range function results
问题描述
范围功能是否允许串联?就像我想做一个 range(30)
&将其与 range(2000,5002)
连接。因此,我的串联范围为 0、1、2,... 29、2000、2001,... 5001
Does range function allows concatenation ? Like i want to make a range(30)
& concatenate it with range(2000, 5002)
. So my concatenated range will be 0, 1, 2, ... 29, 2000, 2001, ... 5001
这样的代码不适用于我最新的python(版本:3.3.0)
Code like this does not work on my latest python (ver: 3.3.0)
range(30) + range(2000, 5002)
推荐答案
您可以使用 itertools.chain
为此:
You can use itertools.chain
for this:
from itertools import chain
concatenated = chain(range(30), range(2000, 5002))
for i in concatenated:
...
可迭代的。请注意, range()的行为有所不同
在Python 2和3之间,您应该了解以下内容:在Python 2中 range
返回一个列表,并在Python3中返回一个迭代器,该迭代器可节省内存,但并不总是可取的。
It works for arbitrary iterables. Note that there's a difference in behavior of range()
between Python 2 and 3 that you should know about: in Python 2 range
returns a list, and in Python3 an iterator, which is memory-efficient, but not always desirable.
列表可以与 +
串联,迭代器不能。
Lists can be concatenated with +
, iterators cannot.
这篇关于连接两个范围函数结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!