比较两个列表中的元素 [英] Comparing elements in two lists

查看:116
本文介绍了比较两个列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个lists.说一个是[6,4,2,1],另一个是[1,3,5,7].我需要比较各个位置的元素(第一个列表的第一个元素与第二个列表的第一个元素进行比较).我需要第三个list,它可以告诉第一个列表中有多少个元素大于第二个列表中的元素.例如,当比较以上两个列表时,第三个列表应类似于[2](因为6 > 14 > 3).我该怎么做

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

推荐答案

您可以使用zip(..) generator :

list3 = [sum(x > y for x,y in zip(list1,list2))]

sum(..)对元素求和,并且由于int(True)1并且int(False)0,因此它计算对x,y的对数,其中x > y.

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.

您可以使用列表理解

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.

这篇关于比较两个列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆