[英]How to split a list into groups of 4 where first elements are greater than the last?
我有這個整數列表,我想按條件將它們分成 4 個元素的組:
result = [0, 4, 10, 6, 15, 9, 18, 35, 40, -30, -90, 99]
每組的第一項應大於以下第四項。 輸出應該是這樣的:
[[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -90]]
但是我如何在這段代碼中應用這些條件?
split_no = 4
list(split_list(result, split_no))
目前我的輸出是這樣的:
[[0, 4, 10, 6], [15, 9, 18, 35], [40, -30, -90, 99]]
您可以執行以下操作
arr1 = [0, 4, 10, 6, 15, 9, 18, 35, 40, -30, -90, 99]
arr2=[arr1[x:x+4] for x in range(0, len(arr1)) if len(arr1[x:x+4])==4]
for each in arr2[:]:
if each[0]<=each[3]:
arr2.remove(each)
現在,如果您嘗試打印出 arr2;
print(arr2)
你得到:
[[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -90]]
首先,使用Python 的 list comprehension創建長度為 4 的所有子列表的列表:
input_list = [0, 4, 10, 6, 15, 9, 18, 35, 40, -30, -90, 99]
all_sublists = [input_list[i:i+4] for i in range(len(input_list)-3)]
print(all_sublists)
# [[0, 4, 10, 6], [4, 10, 6, 15], [10, 6, 15, 9], [6, 15, 9, 18], [15, 9, 18, 35], [9, 18, 35, 40], [18, 35, 40, -30], [35, 40, -30, -90], [40, -30, -90, 99]]
然后,使用所需條件過濾子列表:
output = [sublist for sublist in all_sublists if sublist[0]>sublist[-1]]
print(output)
# [[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -90]]
單行解決方案可能是:
output = [input_list[i:i+4] for i in range(len(input_list)-3)
if input_list[i]>input_list[i+3]]
print(output)
# [[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -90]]
來自xdze2和gireesh4manu 的答案有一個缺點,就是將所有長度為 4 的子序列保留在內存中。 我們可以通過使用滾動窗口迭代器來避免這種情況。
例如,從這個答案中取出一個並稍微改進一下:
from itertools import islice, tee
def windows(iterable, size):
iterators = tee(iterable, size)
iterators = [islice(iterator, i, None) for i, iterator in enumerate(iterators)]
yield from map(list, zip(*iterators))
def is_valid(seq):
return seq[0] > seq[-1]
result = [0, 4, 10, 6, 15, 9, 18, 35, 40, -30, -90, 99]
print(list(filter(is_valid, windows(result, 4))))
會給你:
[[10, 6, 15, 9], [18, 35, 40, -30], [35, 40, -30, -90]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.