集合与列表的区别
集合set: 无序,元素不重复,长度可变
列表list: 有序,元素可重复,具备索引,长度可变
users=set()#创建空集合
users.add('caterpillar')
print(users)
users.add('June')
print(users)
users.add('Mimi')#添加
print(users)
users.remove('Mimi')#删除
print(users)
s=set('哈啰!世界')#无序,元素不重复,长度可变
print(s)
s=list('哈啰!哈啰')
print(s)
s=list('哈啰!世界')#有序,元素可重复,具备索引,长度可变
print(s)
结果如下:
{'caterpillar'}
{'caterpillar', 'June'}
{'Mimi', 'caterpillar', 'June'}
{'caterpillar', 'June'}
{'!', '界', '啰', '哈', '世'}
['哈', '啰', '!', '哈', '啰']
['哈', '啰', '!', '世', '界']
字典
passwords={'June':123456,'Tom':999332}
print(' ', passwords['Tom'])#注意括号类型
passwords['Nini']= 368164
print(passwords)
del passwords['Tom']
print(passwords)
print('Tom' in passwords)
temp=passwords.get('Jenny')
print(temp)
temp=passwords.get('Jenny',9999)#若不存在keyword, 则返回9999
print(temp)
passwords=dict(justin=123456,momor=679897,hamimi=968998)
print(passwords)
结果:
999332
{‘June’: 123456, ‘Tom’: 999332, ‘Nini’: 368164}
{‘June’: 123456, ‘Nini’: 368164}
False
None
9999
{‘justin’: 123456, ‘momor’: 679897, ‘hamimi’: 968998}
元组
#在某个值后面加上逗号就是元组
acct = 'Justin', True, 13
print(acct)
#只包含一个元素的元组不能写成(elem),而要写成(elem,),或者 : elem,
结果
('Justin', True, 13)
>>> data=(1,'June',14)
>>> id, name, age=data
>>> id
1
>>> name
'June'
>>> data
(1, 'June', 14)
>>> age
14
元组的置换
>>> x=20,y=30,z=100
SyntaxError: can't assign to literal
>>> x=20
>>> y=30, z=100
SyntaxError: can't assign to literal
>>> y=30
>>> y= 30, z=100
SyntaxError: can't assign to literal
>>> y=30
>>> z=100
>>> x,y,z=z,x,y
>>> x
100
>>> y
20
>>> z
30
>>>
拓展可迭代拆卸
>>> a, *b=(1,2,3,4,5)
>>> a
1
>>> b
[2, 3, 4, 5]
>>> a,b,c,*d=('a','b','c','d','e','f')
>>> a
'a'
>>> b
'b'
>>> c
'c'
>>> d
['d', 'e', 'f']
>>> a,*b=('True','interesting!')
>>> a
'True'
>>> b
['interesting!']
>>> a,*b=['True','interesting',' book!']
>>> a
'True'
>>> b
['interesting', ' book!']
>>>