需要在set中找到不大于给定变量的最大数字

时间:2013-07-19 17:16:59

标签: python loops indexing set

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

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

3 个答案:

答案 0 :(得分:2)

假设我理解你在问什么,

actual_weight = max([x for x in weights if x <= desired_weight])

答案 1 :(得分: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)

答案 2 :(得分:0)

actual_weight = max([x for x in weights if x <= desired_weight])
weights.remove(actual_weight)