您可以编写一个自定义函数来实现这一点——不需要大量依赖项。请注意,这将返回一个
新
列表可以通过创建一个类来进一步改进这一点:
def generate_list_with_normalization(input_list, element_to_add, cap=100):
total = sum(input_list) + element_to_add
if total <= cap:
return input_list + [element_to_add]
return [elem * cap / total for elem in input_list + [element_to_add]]
my_list = [10, 5, 20, 30, 25, 10]
result = generate_list_with_normalization(my_list, 10, 100)
print(result)
print(sum(result))
这将产生:
[9.090909090909092, 4.545454545454546, 18.181818181818183,
27.272727272727273, 22.727272727272727, 9.090909090909092, 9.090909090909092]
100.0