1

我有一组、重量和一个整数所需的重量。我需要删除列表中最接近但不大于所需重量的元素,并将其与实际重量相关联。这是我的代码到目前为止的样子:

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()
4

3 回答 3

2

假设我明白你在问什么,

actual_weight = max([x for x in weights if x <= desired_weight])
于 2013-07-19T17:25:05.327 回答
0

你可以试试这个:

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)
于 2013-07-19T17:28:27.567 回答
0
actual_weight = max([x for x in weights if x <= desired_weight])
weights.remove(actual_weight)
于 2017-08-31T21:48:21.903 回答