Python - 重新分配修剪后的值
给定一个列表,重新分配由 K 修剪的值。
例子:
Input : test_list = [4, 5, 2, 8, 9, 3, 1, 2, 4], K = 2
Output : [5.0, 11.0, 12.0, 6.0, 4.0]
Explanation : 4, 5, 2, 4 are trimmed, totalling to 15, which dividing by 5 ( size left ) equates 3, which is added to each element.
Input : test_list = [4, 5, 2, 8, 9], K = 2
Output : [28.0]
Explanation : 4, 5, 8, 9 are trimmed, totalling to 26, which dividing by 1 ( size left ) equates 26, which is added to each element.
方法:使用slice() + sum()
在这里,总和使用 sum 计算,列表使用 slice() 进行修剪,然后通过减去总权重来计算修剪后的权重。通过为每个元素添加统一的权重来重新分配。
Python3
# Python3 code to demonstrate working of
# Redistribute Trimmed Values
# Using slice() + sum()
# initializing list
test_list = [4, 5, 2, 8, 9, 3, 1, 2, 4]
# printing original lists
print("The original list is : " + str(test_list))
# initializing K
K = 2
# getting full list sum
full_sum = sum(test_list)
# trimming list
trimd_list = test_list[K:len(test_list) - K]
# getting trimmed list sum
trim_sum = sum(trimd_list)
# getting value to add to each element
add_val = (full_sum - trim_sum) / len(trimd_list)
# adding values
res = [ele + add_val for ele in trimd_list]
# printing result
print("Redistributed list : " + str(res))
输出
The original list is : [4, 5, 2, 8, 9, 3, 1, 2, 4]
Redistributed list : [5.0, 11.0, 12.0, 6.0, 4.0]