假设我正在迭代一个列表。我想检查列表的邻居(I -1和I +1)是否包含某个元素。如何做到这一点,而不会遇到"列表索引超出范围"的情况?问题吗?例子:
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)
我如何设置范围函数的边界,使它不低于0和高于len(list)?
如果要遍历目标列表中的所有元素,一种解决方案是检查第二个for循环的值:
_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
尝试从顶部和底部切片列表
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
或者因为不在外部循环中使用列表项,所以循环遍历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
听起来你想使用窗口函数。我在这里的某个地方得到了这个,并且多年来一直在使用它:
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)
这将给你:
(1,0,1)(0,1,0)(1,0,1)(0,1,0)(1,0,5)
在这里你可以随意比较结果"窗口"的内容。