繁体   English   中英

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

[英]need to find greatest number in set that's not greater than given variable

我有一个设置,权重和整数所需的权重。 我需要删除列表中最接近但不大于所需权重的元素,并将其与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()

假设我了解您的要求,

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM