如何在Python中设置范围函数的限制?
说我在列表中迭代。我想检查列表的邻居(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(列表)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果要迭代目标列表中的所有元素,一个解决方案是检查循环的第二个值:
If you want to iterate for all elements in the target list, one solution is to check the value of second for loop:
尝试从顶部和底部切片列表
,或者因为您不使用外循环中的列表项,请在范围内循环
Try slicing list from the top and bottom
or since you don't use list items in the outer loop, loop over range
听起来您想使用窗口函数。这些年来,我在这里的某个地方一直在使用它:
这将为您提供:
您可以在其中比较结果的“窗口”的内容。
Sounds like you want to use a window function. I got this somewhere here and have been using it over the years:
This will give you :
Where you can compare the contents of the resulting 'window' however you like.