How to create list from 100 elements to list of 10 [duplicate]

故事扮演 提交于 2019-12-25 18:53:53

问题


I have small brain fade today and I believe it will be faster to get hint here than wondering for an hour.

I have list A of 100 elements. How can I create another list(B) basing on list A, that will have 10 elements, so that each element is mean of 10 elements from list A?

Thank you in advance.

e.g.

A = [10,10,10,10,10,20,20,20,20,20,30,30,30,30,30,40,40,40,40,40]
B = [15, 35]

回答1:


A = [i for i in range(100)]
[sum(A[k * 10 : 10*(k+1)])/10 for k in range(len(A)//10)]

Output

[4.5, 14.5, 24.5, 34.5, 44.5, 54.5, 64.5, 74.5, 84.5, 94.5]



回答2:


You can use a list comprehension:

A = [10,10,10,10,10,20,20,20,20,20,30,30,30,30,30,40,40,40,40,40]
B = [sum(A[i:i+10])/10 for i in range(0, len(A), 10)]

print(B)
# [15.0, 35.0]



回答3:


A = [10,10,10,10,10,20,20,20,20,20,30,30,30,30,30,40,40,40,40,40]
B = []

for i in range (0,int(len(A)/10)):
    numbersSum = sum(A[i*10:(i+1)*10])/10
    print(numbersSum)
    B.append(numbersSum)
print(B)


来源:https://stackoverflow.com/questions/57782950/how-to-create-list-from-100-elements-to-list-of-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!