我有一组、重量和一个整数所需的重量。我需要删除列表中最接近但不大于所需重量的元素,并将其与实际重量相关联。这是我的代码到目前为止的样子:
desired_weight = weights[0]
for i in weights:
for x in weights:
if x>i:
if desired_weight <= x:
actual_weight = desired_weight
weights.remove()
假设我明白你在问什么,
actual_weight = max([x for x in weights if x <= desired_weight])
你可以试试这个:
desired_weight = weights[0]
diff = inf
actual_weight = 0
for x in weights:
if x < desired_weight and (x-desired_weight) < diff:
diff = x - desired_weight
actual_weight = x
weights.remove(actual_weight)
actual_weight = max([x for x in weights if x <= desired_weight])
weights.remove(actual_weight)