示例 1,
輸入:[a,b,c,d]
輸出:[[a],[a,b],[b,c],[c,d],[a,b,c],[b,c,d],[a,b,c,d] ]
示例 2,
輸入:[1,2,3,4,5]
輸出:[[1],[1,2],[2,3],[3,4],[4,5],[1,2,3],[2,3,4],[3, 4,5],[1,2,3,4],[2,3,4,5],[1,2,3,4,5]]
以同樣的方式,對中的元素數量從1開始增加到 'n'(給定串列的大小)
是否有一種可能的處理方式,任何大小的給定串列(如果可能在 Python 中)
額外資訊:
我已經嘗試過這段代碼,它在輸出中回傳一對 3 個元素,但我想回傳第一個元素,接下來是 2 個元素,直到我在上面的示例中提到的 n-1 個元素
輸入:
listA = [51,23,11,45]
res = [[listA[i], listA[i 1],listA[i 2]] for i in range(len(listA) - 2)]
print("List with paired elements: \n",res)
輸出:
具有成對元素的串列:[[51, 23, 11], [23, 11, 45]]
uj5u.com熱心網友回復:
第一種方式
您可以使用包自動執行此操作more_itertools.substrings:
import more_itertools
list(more_itertools.substrings([2,3,5,7,11]))
輸出:
[(2,), (3,), (5,), (7,), (11,), (2, 3), (3, 5), (5, 7), (7, 11), (2, 3, 5), (3, 5, 7), (5, 7, 11), (2, 3, 5, 7), (3, 5, 7, 11), (2, 3, 5, 7, 11)]
您還可以檢查此方法的實作源代碼或自己制作作為練習。
第二種方式
它使您可以使用以下方式準確實作您的期望more_itertools.sliding_window:
from itertools import chain
from more_itertools import sliding_window
x = [2,3,5,7,11]
first_part = [(x[0],)]
second_part = [sliding_window(x, n) for n in range(2, len(x) 1)]
list(chain(first_part, *second_part))
輸出:
[(2,), (2, 3), (3, 5), (5, 7), (7, 11), (2, 3, 5), (3, 5, 7), (5, 7, 11), (2, 3, 5, 7), (3, 5, 7, 11), (2, 3, 5, 7, 11)]
uj5u.com熱心網友回復:
我對輸出要求有點困惑,但這是產生我認為您正在尋找的結果的東西:
def get_list_of_size(l, n):
return [l[i:i n] for i in range(len(l)-n 1)]
def get_consecutive_ss(l):
output=[]
for i in range(len(l)):
output =get_list_of_size(l, i 1)
return [output[0]] output[len(l):]
l = [1,2,3,4,5]
l2=['a','b','c','d']
print(get_consecutive_ss(l))
print(get_consecutive_ss(l2))
輸出:
[[1], [1, 2], [2, 3], [3, 4], [4, 5], [1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3, 4], [2, 3, 4, 5], [1, 2, 3, 4, 5]]
[['a'], ['a', 'b'], ['b', 'c'], ['c', 'd'], ['a', 'b', 'c'], ['b', 'c', 'd'], ['a', 'b', 'c', 'd']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/427609.html
下一篇:如何獲取串列中反向重復項的索引
