python技巧31[对象相等性|dictionary模拟switchcase]

本文介绍了Python中不同数据类型(如字符串、元组、列表、字典和自定义对象)的相等性比较规则,并通过实例展示了如何使用字典来实现类似switch case的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一  对象相等性比较

python 对于string,tuple,list,dict,只要内容相等则为相等,但是对于自定义对象则不是。

 

print('---------------str-------------------------')

mystr
=""
mystr2
="test"
mystr3
='test'
if mystr == "" : print('str is empty')
if len(mystr) == 0 : print('str is empty')
if len(mystr2) : print('if not empty, print')

if mystr2 == "test" : print('the strs are equal')
if mystr2 == mystr3 : print('the strs are equal')
if mystr2 != 'aa' : print('the strs are not equal')

print('---------------list------------------------')

mylist
=[]
mylist2
=[1,2,3]
mylist3
=[1,2,3]
if mylist == [] : print('list is empty')
if len(mylist) == 0 : print('list is empty')
if len(mylist2) : print('if not empty, print')


if mylist2 == [1,2,3] : print('the lists are equal')
if mylist2 == mylist3 : print('the lists are equal')
if mylist != [1,2] : print('the lists are not equal')

print('---------------set/dictionary--------------')
myset
={'one','two'}
if myset == {"one",'two'} : print('two sets are equal')

mydict
={'one':1'two':2}
mydict2
={'one':1'two':2}
if mydict == mydict2 : print('two dicts are equal')

print('---------------object----------------------')

class MyClass :
    
def __init__(self,x,y):
        self.x 
= x
        self.y 
= y

if MyClass(1,2!= MyClass(1,2) : print('the two objects are not equal')

print('---------------end------------------------')

 

结果:

---------------str-------------------------
str is empty
str is empty
if not empty, print
the strs are equal
the strs are equal
the strs are not equal
---------------list------------------------
list is empty
list is empty
if not empty, print
the lists are equal
the lists are equal
the lists are not equal
---------------set/dictionary--------------
two sets are equal
two dicts are equal
---------------object----------------------
the two objects are not equal
---------------end------------------------ 


 二 dictionary来模拟switchcase
def key_1_pressed():
    
print ('Key 1 Pressed')

def key_2_pressed():
    
print ('Key 2 Pressed')

def key_3_pressed():
    
print ('Key 3 Pressed')

def unknown_key_pressed():
    
print ('Unknown Key Pressed')
    
keycode 
= 2
if keycode == 1:
   key_1_pressed()
elif keycode == 2:
   key_2_pressed()
elif number == 3:
   key_3_pressed()
else:
   unknown_key_pressed()


keycode2 
= 2
functions 
= {1: key_1_pressed, 2: key_2_pressed, 3: key_3_pressed}
functions.get(keycode2, unknown_key_pressed)()


完!

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值