過去我一直在尋找如何做到這一點,但似乎找不到任何可以回答我的問題的東西,或者它的想法和代碼對于我作為一個完整的初學者來說太復雜而無法理解。所以基本上這是我必須做的任務:
撰寫一個函式 all sublists(lst) ,對于串列 lst,它回傳一個包含 lst 的所有子串列的串列作為其結果。子串列是包含原始的連續部分的串列,即包含來自原始的零個或多個連續元素。
例如,對于串列 [1, 2, 3] 結果應該是
[[], [1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]
我開始做的是創建一個包含所有數字的完整串列,然后將其拆分。但是我不能使用 split 函式,因為它是一個字串,并且不知道正確拼接它的任何正確方法。
uj5u.com熱心網友回復:
利用 itertools.combinations
from itertools import combinations
l = [1, 2, 3]
final = []
for i in range(len(l) 1):
final = list(combinations(l,i))
print(final)
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
uj5u.com熱心網友回復:
這是一個使用雙回圈找到所需結果的函式。
def get_contiguous_sublists(lst):
out = [[]]
# find the length of the input list (added 1 for convenience which will be useful later)
len_lst = len(lst) 1
# for each integer between 1 and the full length of the input list,
# we slice the input list `lst` to create new lists of this length
# and add it to the output list `out`
for length in range(1, len_lst):
# here, we are changing the starting point of the list slicing,
# i.e. whether we want to start from 1 or 2 or 3 for [1,2,3]
for i in range(len_lst - length):
out = [lst[i : i length]]
return out
輸出:
>>> get_contiguous_sublists([1,2,3])
[[], [1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]
>>> get_contiguous_sublists([1,2,3,4])
[[], [1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [1, 2, 3], [2, 3, 4], [1, 2, 3, 4]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388332.html
下一篇:獲取接近串列末尾的元素索引
