Comparing Elements In Two Lists
I have two lists. Say one is [6,4,2,1] and the other is [1,3,5,7]. I need to compare elements of respective positions (first element of first list compared with first element of
Solution 1:
You can do this with zip(..) and a generator:
list3 = [sum(x > y for x,y in zip(list1,list2))]
sum(..) sums over the elements and since int(True) is 1 and int(False) is 0, it thus counts the number of pairs x,y where x > y.
You can boost performance a bit by using list comprehension:
list3 = [sum([x > y for x,y in zip(list1,list2)])]
But I do not really see why you construct a list, a simple integer is enough.
Post a Comment for "Comparing Elements In Two Lists"