简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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