繁体   English   中英

如何将列表分成 4 个一组,其中第一个元素大于最后一个?

[英]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]]

来自xdze2gireesh4manu 的答案有一个缺点,就是将所有长度为 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM