How can I add non-sequential numbers to a range?

烈酒焚心 提交于 2019-12-22 04:19:12

问题


I am trying to iterate through the range(750, 765) and add the non-sequential numbers 769, 770, 774. If I try adding the numbers after the range function, it returns the range list, then the individual numbers:


>>> for x in range(750, 765), 769, 770, 774: print x
... 
[750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764]
769
770
774

How can I get all the numbers in a single list?


回答1:


Use the built-in + operator to append your non-sequential numbers to the range.

for x in range(750, 765) + [769, 770, 774]: print x



回答2:


There are two ways to do it.

>>> for x in range(5, 7) + [8, 9]: print x
...
5
6
8
9
>>> import itertools
>>> for x in itertools.chain(xrange(5, 7), [8, 9]): print x
...
5
6
8
9

itertools.chain() is by far superior, since it allows you to use arbitrary iterables, rather than just lists and lists. It's also more efficient, not requiring list copying. And it lets you use xrange, which you should when looping.




回答3:


The other answers on this page will serve you well. Just a quick note that in Python3.0, range is an iterator (like xrange was in Python2.x... xrange is gone in 3.0). If you try to do this in Python 3.0, be sure to create a list from the range iterator before doing the addition:

for x in list(range(750, 765)) + [769, 770, 774]: print(x)



回答4:


are you looking for this:

mylist = range(750, 765)
mylist.extend([769, 770, 774])



回答5:


In python3, since you cannot add a list to a range, if for some reason, you do not wish to import itertool, you can also do the same thing manually:

for r in range(750, 765), [769, 770, 774]:
    for i in r: 
        print(i)

or

for i in [i for r in [range(750, 765), [769, 770, 774]] for i in r]: 
    print(i)


来源:https://stackoverflow.com/questions/678410/how-can-i-add-non-sequential-numbers-to-a-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!