Iterate Two Ranges In For Loop

后端 未结 3 1185
说谎
说谎 2021-01-02 10:13

I have a couple of simple loops like so:

for i in range (30, 52):

    #do some stuff here

for i in range (1, 18):

    #do some more stuff
<
相关标签:
3条回答
  • 2021-01-02 10:57
    for i in range(30, 52) + range(1, 18):
        #something
    
    0 讨论(0)
  • 2021-01-02 10:58

    You can convert the two iterators for your ranges to lists and then combine them with an addition:

    for i in list(range(30, 52)) + list(range(1, 18)):
        # something
    
    0 讨论(0)
  • 2021-01-02 11:04

    From https://docs.python.org/2/library/itertools.html#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. Used for treating consecutive sequences as a single sequence.

    Example:

    import itertools as it
    for i in it.chain(range(30, 52), range(1, 18)):
        print(i)
    
    0 讨论(0)
提交回复
热议问题