问题
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