我试图用Python编写一个函数,在输入一个最大值时查找一个列表,它将限制列表中的值,并按比例将从该数字中减去的多余值重新分配给列表中的其他数字。你知道吗
例如,我希望通过最大值为0.3的函数传递的[0.05,0.02,0.05,0.08,0.80]为[0.175,0.07,0.175,0.28,0.30]。你知道吗
目前,我在Python中有这样的东西:
''
import numpy as np
x = np.array([0.05, 0.05, 0.02, 0.08, 0.80])
limit = 0.3
excess = 0
y = np.zeros(len(x))
z = np.zeros(len(x))
for i in range(len(x)):
if x[i] > limit:
excess = x[i] - limit
x[i] = 0
y[i] = limit
z = x*(1/sum(x)*excess)
z = z+x+y
''
其中z是这个特定数组的结果。你知道吗
''
z = array([0.175, 0.175, 0.07 , 0.28 , 0.3 ])
''
但是,如果有多个数字超出限制,或者数组的顺序不同,就会出现这种情况。你知道吗
您可以使用以下脚本实现您的目标。这个想法是采取“多余的重量”,并重新分配它对体重不足的元素反复,直到所有的元素已被封顶。这个过程需要重复,因为重新分配可能会使一些原本体重不足的因素超过上限。另外,您没有明确提到它,但是基于finance标签和您的示例,我假设列表的总和需要保持不变。你知道吗
首先,我创建了一个pandas数据帧,其中包含20个值,求和为1,并按降序排列。你知道吗
第二,我们把上限设为0.06。这将使它成为您面临的多重超重元素问题的一个很好的测试用例。你知道吗
下面是迭代脚本。你知道吗
然后可以将结果重新分配到数据帧并进行比较。你知道吗
元素M是一个很好的例子,说明了为什么需要一个重复的过程。它原本体重不足,但如此接近上限,以至于在第一次重新分配后会变得超重。你知道吗
相关问题 更多 >
编程相关推荐