[英]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.
我想检查列表的邻居(i-1 和 i+1)是否包含某个元素。 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)?如何为 range 函数设置边界,使其不会低于 0 和高于 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:如果要迭代目标列表中的所有元素,一种解决方案是检查第二个 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
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)
(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.您可以随意比较生成的“窗口”的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.