02.集合类简单操作

#list:list是一种有序的集合,可以随时添加和删除其中的元素
#tuple:tuple和list非常类似,但是tuple一旦初始化就不能修改
#dict:dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度
#

print('##########################################list################################')
#定义list
list=['a','b',1]
#追加
list.append(2)
list.append(2)
print(list)
#插入
list.insert(0,'hello')
print(list)
#删除
list.pop()
print(list)
#替换
list[1]='word'
print(list)
#统计元素数量
print(list.count(2))
#倒数第3个元素
print(list[-3])
#元素反转
list.reverse()
print(list)
print(type(list))

print('##################################tuple#######################################')
tuple=('hello','word','hi','yes',['tom','jack'])
print(tuple)
print(tuple[-3])
#tuple不可变,但是他的元素可变
tuple[-1][0]='哈哈'
print(tuple)
print(type(tuple))

print('##################################dict#######################################')
dict = {'a':0,'b':1,'c':2,'d':3}
print(dict['c'])
#覆盖
dict['d']=4
print(dict)
#增加
dict['e']=5
#用get取值不存在不会报错,并且可以指定默认值
print(dict.get('f','0'))
print(dict)
#删除
dict.pop("a")
print(dict)

print('##################################set#######################################')
set = set([1,2,3,3,4,5,6,7,8,5])
print(set)
set.add(9)
print(set)
set.remove(1)
print(set)

C:\Users\Administrator.000\AppData\Local\Programs\Python\Python36\python.exe E:/python/集合类.py
##########################################list################################
['a', 'b', 1, 2, 2]
['hello', 'a', 'b', 1, 2, 2]
['hello', 'a', 'b', 1, 2]
['hello', 'word', 'b', 1, 2]
1
b
[2, 1, 'b', 'word', 'hello']
<class 'list'>
##################################tuple#######################################
('hello', 'word', 'hi', 'yes', ['tom', 'jack'])
hi
('hello', 'word', 'hi', 'yes', ['哈哈', 'jack'])
<class 'tuple'>
##################################dict#######################################
2
{'a': 0, 'b': 1, 'c': 2, 'd': 4}
0
{'a': 0, 'b': 1, 'c': 2, 'd': 4, 'e': 5}
{'b': 1, 'c': 2, 'd': 4, 'e': 5}
##################################set#######################################
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{2, 3, 4, 5, 6, 7, 8, 9}


Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_34908148/article/details/80376441