简体   繁体   English

如何将 function 应用于列表中的每组三个?

[英]How to apply a function to every set of three in a list?

The list is 2, 4, 5, 1, 2, 3, 3, 5, 1 How would I get the output to be列表是 2、4、5、1、2、3、3、5、1 我将如何获得 output

2,4,5 2,4,5

1,2,3 1,2,3

3,5,1 3,5,1

And then be able to apply a function to each of these three lists?然后能够将 function 应用于这三个列表中的每一个?

its simple这很简单

mylist = [2, 4, 5, 1, 2, 3, 3, 5, 1]
subset_len = 3
print([mylist[subset_len*i:subset_len*(i+1)] for i in range(len(mylist)//subset_len)])

You can try with this:你可以试试这个:

data = [2, 4, 5, 1, 2, 3, 3, 5, 1]

elements_for_list = 3

splitted_data = [data[i: i+elements_for_list] for i in range(0, len(data), elements_for_list)]

for values in splitted_data:
    # apply the sum function on each list
    print(sum(values))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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