Python 5 字典,集合

字典创建
>>>a={‘a’:’animal’,’b’:’human’}

用内置函数dict()快速创建字典
>>> keys=['a','b','c','d']
>>> values=[1,2,3,4]
>>> adict=dict(zip(x,y))
>>> print(adict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

>>> adict=dict(name='wang',age='22')
>>> adict
{'name': 'wang', 'age': '22'}




字典元素增加,修改

>>> keys=['name','sex','age']
>>> values=['hua','male','21']
>>> d=dict(zip(keys,values))
>>> d
{'name': 'hua', 'sex': 'male', 'age': '21'}
>>> d['age']=99
>>> d
{'name': 'hua', 'sex': 'male', 'age': 99}
>>> d['address']='hubei'
>>> d
{'name': 'hua', 'sex': 'male', 'age': 99, 'address': 'hubei'}


update()函数
>> d      
{'name': 'hua', 'sex': 'male', 'age': 99, 'address': 'hubei'}
>>> d.update({'age':22,'q':11})
d          
{'name': 'hua', 'sex': 'male', 'age': 22, 'address': 'hubei', 'q': 11}



del删除命令

>>> d      
{'name': 'hua', 'sex': 'male', 'age': 99, 'address': 'hubei', 'q': 11}
>>> d     
{'name': 'hua', 'sex': 'male', 'age': 99, 'address': 'hubei', 'q': 11}
>>> del d['age']    
>>> d
{'name': 'hua', 'sex': 'male', 'address': 'hubei', 'q': 11}
>>> del d    
>>> d
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    d
NameError: name 'd' is not defined




setdefault(键,值 )

存在则返回,不存在则创建

>>> adict.setdefault('address','beijing')
'beijing'
>>> adict   
{'age': 22, 'name': 'huaqiao', 'sex': 'male', 'address': 'beijing'}
>>>


字典的遍历 

当对字典遍历输出时,默认输出字典的键
>>> for i in adict:
       print(i)

       
age
name
sex
address
>>>

items()返回字典的键值
>>> for i in adict.items():
       print(i)

       
('age', 22)
('name', 'huaqiao')
('sex', 'male')
('address', 'beijing')
>>>


items(),keys(),values()

>>> adict.items()       
dict_items([('age', 22), ('name', 'huaqiao'), ('sex', 'male'), ('address', 'beijing')])

>>> adict.keys()       
dict_keys(['age', 'name', 'sex', 'address'])

>>> adict.values()       
dict_values([22, 'huaqiao', 'male', 'beijing'])
>>>

集合set


和字典一样用大括号{}作为界定符,元素唯一,不可重复。

集合创建:“=”

>>> q={1,2,3,4,5}
>>> q
{1, 2, 3, 4, 5}
>>>

Set转换
>>> a=set([1,2,3,4,5])
>>> a
{1, 2, 3, 4, 5}
>>>


集合元素增加add(),update( )

>>> k={1,2,3,4}
>>> k.add(999)
>>> k
{1, 2, 3, 4, 999}

>>> b={111,222}
>>> k.update(b)
>>> k
{1, 2, 3, 4, 999, 111, 222}

集合元素删除

pop(x):删除并返回最左边的一个元素
remove(要删除的元素):
discard(要删除的元素):
clear():

集合运算

>>> a={1,2,3}
>>> b={3,4,5,6}
>>> a|b                        #并集
{1, 2, 3, 4, 5, 6}
>>> a&b                        #交集
{3}
>>> a-b                         #差集
{1, 2}
>>>
>>> a.symmetric_difference(b)
{1, 2, 4, 5, 6}                         #对称差集









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值