python中比较两个列表的实例方法

yipeiwu_com6年前Python基础

cmp() 方法用于比较两个列表的元素。

cmp()方法语法

cmp(list1, list2)

参数:

list1 -- 比较的列表。list2 -- 比较的列表。

返回值:

如果比较的元素是同类型的,则比较其值,返回结果。

如果两个元素不是同一种类型,则检查它们是否是数字。

如果是数字,执行必要的数字强制类型转换,然后比较。如果有一方的元素是数字,则另一方的元素"大"(数字是"最小的")否则,通过类型名字的字母顺序进行比较。

如果有一个列表首先到达末尾,则另一个长一点的列表"大"。

如果我们用尽了两个列表的元素而且所 有元素都是相等的,那么结果就是个平局,就是说返回一个 0。

以下实例展示了 cmp()函数的使用方法:

#!/usr/bin/python

list1, list2 = [123, 'xyz'], [456, 'abc']

print cmp(list1, list2);

print cmp(list2, list1);

list3 = list2 + [786];

print cmp(list2, list3)

Python3不在支持cmp方法:

可用方法有:

表达式减(-)法:

print((a>b)-(a<b)) #0,表示俩list相等

operator模块比较运算

import operator

 

a=[1, 2, 3, 4, 5 ]

b=[1, 2, 3, 4, 5,6 ]

c=[1, 2, 3, 4, 5 ]

print(operator.lt(a,b)) #=> True ,小于<

print(operator.gt(a,b)) #=> False ,大于>

print(operator.eq(a,c)) #=> True ,等于==

print(operator.ne(b,a)) #=> True ,不等于!=

print(operator.le(a,b)) #=> True ,小于等于<=

print(operator.ge(b,a)) #=> True ,大于等于>=

扩展学习:

两个列表,随机产生4个不相等的数,计算一下,相同位置上的元素相等的个数,用k1表示。

b列表中的元素在a列表中,但位置不相同,有多少个,用k2表示。

例如:

a=[0, 4, 7, 3]
b=[7, 1, 0, 3]

k1= 1 (只有第4个元素相等,k1=1)
k2= 2(两个列表中都有0和7,但位置不同,k2=2)

a=[]
b=[]
while(len(a)!=4):
  x=randint(0,9)
  if x not in a:
    a.append(x)
    
while(len(b)!=4):
  x=randint(0,9)
  if x not in b:
    b.append(x)
    
print(a)
print(b)
print()
k1=k2=0
for i in range(4):
  if a[i]==b[i]:
    k1+=1
  if b[i] in a and b[i]!=a[i]:
    k2+=1
    
print('k1=',k1)
print('k2=',k2)

相关文章

Ubuntu 下 vim 搭建python 环境 配置

1. 安装完整的vim # apt-get install vim-gnome 2. 安装ctags,ctags用于支持taglist,必需! # apt-get instal...

推荐11个实用Python库

推荐11个实用Python库

1) delorean 非常酷的日期/时间库 复制代码 代码如下: from delorean import Delorean EST = "US/Eastern" d = Delor...

python处理按钮消息的实例详解

python处理按钮消息的实例详解

python处理按钮消息的实例详解            最新学习Python的基础知...

微信跳一跳小游戏python脚本

微信跳一跳小游戏python脚本

Python编写微信小游戏“跳一跳”的运行脚本,分享给大家。 更新了微信后发现了一款小游戏跳一跳,但是玩了一下午最高才达到200,每次差点破纪录后总是手抖就挂掉了,气的想要砸手机。闲来无...

在python中bool函数的取值方法

bool是Boolean的缩写,只有真(True)和假(False)两种取值 bool函数只有一个参数,并根据这个参数的值返回真或者假。 1.当对数字使用bool函数时,0返回假(Fal...