Skip over a value in the range function in python

前端 未结 7 983
我在风中等你
我在风中等你 2020-12-04 17:28

What is the pythonic way of looping through a range of numbers and skipping over one value? For example, the range is from 0 to 100 and I would like to skip 50.

Edi

相关标签:
7条回答
  • 2020-12-04 17:55
    for i in range(100):
        if i == 50:
            continue
        dosomething
    
    0 讨论(0)
  • 2020-12-04 18:05

    You can use any of these:

    # 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
    
    0 讨论(0)
  • 2020-12-04 18:08

    In addition to the Python 2 approach here are the equivalents for 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)
    

    Ranges are lists in Python 2 and iterators in Python 3.

    0 讨论(0)
  • 2020-12-04 18:15

    It depends on what you want to do. For example you could stick in some conditionals like this in your comprehensions:

    # get the squares of each number from 1 to 9, excluding 2
    myList = [i**2 for i in range(10) if i != 2]
    print(myList)
    
    # --> [0, 1, 9, 16, 25, 36, 49, 64, 81]
    
    0 讨论(0)
  • 2020-12-04 18:17

    what you could do, is put an if statement around everything inside the loop that you want kept away from the 50. e.g.

    for i in range(0, len(list)):
        if i != 50:
            x= listRow(list, i)
            for j in range (#0 to len(list) not including x#)
    
    0 讨论(0)
  • 2020-12-04 18:18
    for i in range(0, 101):
    if i != 50:
        do sth
    else:
        pass
    
    0 讨论(0)
提交回复
热议问题