【问题标题】:search aggregation result in main list在主列表中搜索聚合结果
【发布时间】:2022-01-13 10:33:49
【问题描述】:

我想通过catch_list_7=[100,7]导航来检查元素的总和是否在df = [200,107,25,30]中,但是当我输入200时,它比总和更大,我的循环保持在 200 并且不会继续。当我删除 200 值时,它可以工作。

                is_match =False
                for i in catch_list_7 :
                    if is_match ==False:
                           for d in df: 
                            if abs(d-(i[0]+i[1]))<=0.2:
                                catch_list.append([i[0]+i[1],i[0],i[1]])
                                print("Total Gross", catch_list)
                                is_match = True
                                break
                            else: 
                                break

【问题讨论】:

  • 不确定我是否理解您的目标
  • 如果catch_list_7=[100,7] 那么for i in catch_list_7 将使i 成为一个整数,那么你索引i[0] 等,这不是整数的工作方式,应该给你一个TypeError: 'int' object is not subscriptable 但作为你告诉我们代码运行然后我猜你上面的粘贴包含错别字所以请更新它。
  • 我没有收到任何错误。如果我在列表中添加一个大于 107 的值,for 不会返回(比如 200),但是如果我在列表中添加一个小的值,则没有问题。
  • 结果应该是 catch_list=[107,100,7] 但我可以通过删除 200 得到它

标签: python arrays list math


【解决方案1】:

我建议将你的代码封装成函数;每个做一件精确事情的逻辑块应该是一个功能。

这将使每个人都更容易理解您的代码。 “每个人”是指:阅读您的问题的 StackOverflow 用户;你的同事;更重要的是,现在的你自己;一个月后,当你用新的眼光审视自己的代码时。

所以,创建一个小函数,它接受一个值列表和一个目标总和列表,并检查两个值是否添加到一个目标:

from itertools import combinations

def catch_pairs_that_add_to_target(values, targets):
    targets_set = set(targets)
    caught_pairs = []
    for x,y in combinations(values, 2):
        if x + y in targets_set:
            caught_pairs.append((x,y))
    return caught_pairs

# TESTING
print( catch_pairs_that_add_to_target([100, 42, 7, 158], [200, 107, 25, 30]) )
# [(100, 7), (42, 158)]

如果我们正在处理浮点数,我们不应该测试精确相等;这种情况下有math.isclose

from itertools import combinations
from math import isclose

def catch_pairs_that_add_to_target(values, targets):
    caught_pairs = []
    for x,y in combinations(values, 2):
        if any(isclose(x + y, z, abs_tol=0.2) for z in targets):
            caught_pairs.append((x,y))
    return caught_pairs

# TESTING
print( catch_pairs_that_add_to_target([100.1, 42.05, 7.07, 158.1], [200.0, 107.0, 25.0, 30.0]) )
# [(100.1, 7.07), (42.05, 158.1)]

相关文档:

  • itertools.combinations 迭代所有值对;
  • set 因为如果targets 是一个集合,x + y in targets 比如果它是一个列表要快得多;
  • math.isclose 测试浮点的近似相等性;
  • any 检查是否至少有一个元素满足谓词。

【讨论】:

  • 感谢您的帮助。实际上,我分享了作为方法编写的作品的相关部分。感谢您,我的问题得到了解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 2017-03-10
  • 2012-04-18
  • 2021-03-08
相关资源
最近更新 更多