【问题标题】:Duplicate Values in For LoopFor循环中的重复值
【发布时间】:2021-01-12 08:46:15
【问题描述】:

当我打印“金额”时,我得到了重复的值。这是否与我的前三行中的两个 for 循环有关?

缺失金额:

['102,131.49']

预期结果:

102,131.49

实际结果:

102,131.49
102,131.49

代码: 身体_l = [] 对于 url 中的链接: body = browser.find_element_by_xpath("//[contains(text(), 'Total:')]").text body_l.append(正文) icl_dollar_amount = re.findall('(?:[\£$\€]{1}[,\d]+.?\d)', body)[0].split('$', 1 )[1] icl_dollar_amount_l.append(icl_dollar_amount) 如果没有缺失金额: logging.info("列表为空") print("列表为空") 计数 = 0 对于missing_amount中的金额: 对于计数,枚举中的项目(icl_dollar_amount_l): 如果金额 == 项目: 身体 = body_l[计数] get_company_id = body.split("客户 ID:", 1)[1][4:10].strip() 别的: amount_ack_missing_l.append(金额) logging.info("缺失" + str(数量)) print("缺少" + str(数量))

使用 AgentJRock 代码:

当我 print(icl_dollar_amount[i]) 和 missing_amount[i] 时,我的 if 语句从不运行,只有 else 运行。但两个列表的值相同,请参见下文。

for i in range(len(missing_amount)):
    print("Missing Amount : ", missing_amount[i])
    print("ICL DOLLAR", icl_dollar_amount_l[i])
    if missing_amount[i] == icl_dollar_amount_l[i]:
        body = body_l[i]
        get_company_id = body.split("Customer Id:", 1)[1][4:10].strip()
    else:
        amount_ack_missing_l.append(missing_amount[i])
        logging.info("Missing " + str(missing_amount[i]))
        print("Missing " + str(missing_amount[i]))

打印(icl_dollar_amount[i]

ICL DOLLAR 2,760,127.58
ICL DOLLAR 325,845.84

打印(缺失金额[i])

Missing Amount :  325,845.84
Missing Amount :  2,760,127.58

【问题讨论】:

    标签: python


    【解决方案1】:

    你有print("Missing " + str(amount)),但也有logging.info("Missing " + str(amount))。我不知道 logging.info 做了什么,但我认为它会打印到标准输出。我建议您删除 print("Missing " + str(amount))

    【讨论】:

      【解决方案2】:

      是的,你是对的,内循环得到你的两次missing_amount。

      缺失金额、icl_dollar_amount_l 和 body_l 中有哪些类型/值?

      去掉缺失值是一个整数列表 和 icl_dollar_amount_l 是另一个列表整数 而 bod_l 是字典

      您最好使用一个 for 循环来从列表长度范围内创建索引。从 for 循环中的这个索引,您可以比较两个共享索引列表之间的索引。我认为您正在尝试与您的 dict 共享此索引,这对于我们创建的同一索引应该没有问题

      另外,您在 for 循环之外有一个 count 变量,但已将另一个 count 实例设置为 enumerate 变量。

      外部计数需要与设置为该变量的 (+=/-+) 一起使用,这相当于枚举和冗余。

      for i in range(len(missing_amount)):
          if missing_amount[i] == icl_dollar_amount_l[i]:
              body = body_l[i]
              get_company_id = body.split("Customer Id:", 1)[1][4:10].strip()
          else:
              amount_ack_missing_l.append(missing_amount[i])
              logging.info("Missing " + str(missing_amount[i]))
              print("Missing " + str(missing_amount[i]))
      

      【讨论】:

      • 谢谢。我的 If 语句现在永远不会运行或为真。我运行 print(missing_amount[i] 和 print(icl_dollar_amount[i] 时的输出在我编辑的帖子中
      • 另外,body_l 是一个列表。我正在附加身体。查看我编辑的代码。
      • 太棒了,我很高兴你想通了,我可以帮忙
      • 如果您可以帮助其他程序员并单击检查以接受我的回答,我们将不胜感激
      猜你喜欢
      • 2020-10-18
      • 2011-04-20
      • 2012-10-24
      • 2017-03-12
      • 1970-01-01
      • 2019-04-09
      • 2014-01-12
      • 1970-01-01
      • 2016-10-04
      相关资源
      最近更新 更多