简体   繁体   中英

How do I set limits for my range function in python?

Say I am iterating through a list. I want to check if the list's neighbours (i-1 and i+1) contain a certain element. How do I do this without running into "list index out of range" problem? Example:

list = [1, 0, 1, 0, 1, 0]
for i, j in enumerate(list):
    elements = 0
    for m in range(i-1,i+2):
        if list[m] == 1:
            elements += 1
    print(list[i], elements)

How do I set boundaries for the range function, so that it doesn't go below 0 and above len(list)?

Try slicing list from the top and bottom

list = [1, 0, 1, 0, 1, 0]
elements = 0
# slice list and start from second element and finish at the penultimate element
for i, j in enumerate(list[1:-1], 1):
    for m in range(i-1,i+2):
        if list[m] == 1:
            elements += 1

or since you don't use list items in the outer loop, loop over range

elements = 0
# start from the second index and finish at the penultimate index
for i in range(1, len(list)-1):
    for m in range(i-1,i+2):
        if list[m] == 1:
            elements += 1

If you want to iterate for all elements in the target list, one solution is to check the value of second for loop:

_list = [1, 0, 1, 0, 1, 0]
elements = 0
for i, j in enumerate(_list):
    for m in range(max(i-1, 0), min(i+2, len(_list))):
        if _list[m] == 1:
            elements += 1

Sounds like you want to use a window function. I got this somewhere here and have been using it over the years:

from typing import Generator
from itertools import islice

def window(seq, n: int = 2) -> Generator:
    """
    Returns a sliding window (of width n) over data from the iterable
    """
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result
        

mylist = [1, 0, 1, 0, 1, 0, 5]
for chunk in window(mylist, n=3):
    print(chunk)

This will give you :

(1, 0, 1) (0, 1, 0) (1, 0, 1) (0, 1, 0) (1, 0, 5)

Where you can compare the contents of the resulting 'window' however you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM