简体   繁体   中英

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 second list). I need a third list such that it tells how many elements in first list are greater than elements of second list.For example when the above two lists are compared,the third list should be like [2] ( because 6 > 1 and 4 > 3 ). How can I do this

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.

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