简体   繁体   English

为什么一行 python 循环和传统循环返回不同的结果?

[英]why one line python loop and traditional loop return different results?

I have array, where I for sure know, there are two objects, which meet conditions, that I want to loop我有数组,我肯定知道,有两个满足条件的对象,我想循环

if I do如果我做

def filter_checks_by_lcode_and_admin(admin_uid, lcode, checks):

    result = []
    for check in checks:
      if check.lcode == lcode and check.admin == admin_uid:
         result.append(check)
    return result

returns correct array with 2 objects返回包含 2 个对象的正确数组

but this code但是这段代码

def filter_checks_by_lcode_and_admin(admin_uid, lcode, checks):
    return [check for check in checks if check.admin == admin_uid and check.lcode == lcode]

return 0返回 0

what im I doing wrong ?我做错了什么?

Until we have a sample input, we can only speculate.在我们有样本输入之前,我们只能推测。 In principle both versions of your code should be equivalent, but just to be sure write the conditions in the same order in both:原则上,您的代码的两个版本应该是等效的,但要确保在两个版本中以相同的顺序编写条件:

def filter_checks_by_lcode_and_admin(admin_uid, lcode, checks):
    return [check for check in checks if check.lcode == lcode and check.admin == admin_uid]

If that changes the result, then it's because your code has some kind of side effect that makes the result be different between invocations depending on the order of execution.如果这改变了结果,那是因为您的代码有某种副作用,根据执行顺序,调用之间的结果会有所不同。 Certainly something to avoid, as you can see, it'll lead to hard to find bugs.正如您所看到的,当然要避免某些事情,这将导致很难找到错误。

Also you can try executing your code with the same input, but trying the second snippet first and the first snippet later.您也可以尝试使用相同的输入执行代码,但先尝试第二个片段,然后再尝试第一个片段。 If this works, then again it'll be a sign that something is changing the state of the inputs between executions, definitely a problem that should be fixed.如果这有效,那么这将再次表明某些东西正在改变执行之间的输入状态,这绝对是一个应该解决的问题。

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

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