[英]Python: how to iterate over list of list while iterating over each item in each nested list
[英]Iterate over slices of n elements to the left and right of each item in a list in python
假設我有以下列表:
>>> my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
我想編寫一個函數,該函數將在此列表的每個項目的左側和右側迭代n
元素的切片:
def sliding_window_n_elements_left_and_right(lst, n):
...
該函數應該像這樣工作:
>>> list(sliding_window_n_elements_left_and_right(my_list, 0))
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
>>> list(sliding_window_n_elements_left_and_right(my_list, 1))
[[0, 1], [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10]]
>>> list(sliding_window_n_elements_left_and_right(my_list, 2))
[[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10]]
感謝您的時間和技能!
您可以在每個索引處對列表進行切片i
在左側和右側填充n
以創建最大大小2n+1
的固定窗口:
def sliding_window_n_elements_left_and_right(lst, n):
# start = max(0, i-n) prevents slice from starting at negative value
return [lst[max(0, i-n):i+n+1] for i in range(len(lst))]
print(sliding_window_n_elements_left_and_right(my_list, 0))
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
print(sliding_window_n_elements_left_and_right(my_list, 1))
# [[0, 1], [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10]]
print(sliding_window_n_elements_left_and_right(my_list, 2))
# [[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.