简体   繁体   中英

Comparing elements in two lists in python

I have a function that compares the elements of two lists and returns the difference between them. I have two versions of it. The first one works but not the second one. What is wrong with the second function? The inputs a and b are two lists of same length.

def compareLists(a, b):
    A = sum([1 if i > j else 0 for i, j in zip(a, b)])
    B = sum([1 if j > i else 0 for i, j in zip(a, b)])
    return (A, B)

def compareLists(a, b):
    A = sum([1 for i in range(0, len(a)) if a[i] > b[i] else 0])
    B = sum([1 for i in range(0, len(a)) if b[i] > a[i] else 0])
    return (A, B)

Eg input and output: a = [1, 2, 3,4] ; b = [0, -2, 5, 6] ; output = (2, 2)

You don't need the ternary operator ( if-else ) in the second code since using the if expression in a list comprehension is how the output can be filtered:

A = sum([1 for i in range(0, len(a)) if a[i] > b[i]])
B = sum([1 for i in range(0, len(a)) if b[i] > a[i]])

Adding else as you do in your second code makes the syntax invalid.

For completeness, as @wim noted in the comment, the use of the ternary operator is unnecessary in your first code either because Boolean values in Python are simply integers of 1 and 0 , so you can output the Boolean values returned by the comparison operators directly instead:

A = sum([i > j for i, j in zip(a, b)])
B = sum([j > i for i, j in zip(a, b)])

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