Python:列表、元组、集合、字典

1.问题

在这里插入图片描述

2. 代码

# 列表
alist = [1, 2, 3, 4, 5]
blist = alist[1:3]  # 访问列表,用中括号
clist = alist[2 : : -1] # 从第2个,到第一个,用:
dlist = alist[: : 2] # 省略端点值,表示全部

# 元组
atuple = (1, 2, 3, 4, 5)
btuple = atuple[1:3] # 元组的访问,也是用中括号
ctuple = atuple[2::-1]

# 字符串
t = 'Mike and Tom'
t1 = t.split()
t2 = '/'.join(t1) # 用/连接各个字符

# 集合
a = {
    
    1, 2, 3, 4, 5}
b = {
    
    2, 4, 6, 8, 10}

cunion = a.union(b) # 并 |
cinter = a.intersection(b) # 交 &
cdiff = a.difference(b) # 差 -
cissu = a.issubset(b) # 子集 <=
csym = a.symmetric_difference(b) # 异或 ^
a.remove(2) # 错误示范:c = a,remove(2) print(c) ;
a.add(12)
a.clear() # 输出set()
aresult = not a  #非空输出为false
# 不要通过取字符串或者集合的长度来判断是否为空,
# 而是要用not关键字来判断,因为当字符串或集合为空时,
# 其值被隐式地赋为False,这样可以带来性能的提升

# 字典
mydic = {
    
    'name':'Tom', 'age':19, 'contury':'china'}
print(mydic.keys())  # 取键
print(mydic.values())  # 取值
print('name' in mydic)  # 判断键 是否在字典中
print(not mydic)  # 判断是否为空集,空则返回true
mydic['weight'] = 80  # 增加元素
mydic.pop('weight')  # 删除元素
del mydic['age']
print(mydic)

猜你喜欢

转载自blog.csdn.net/qq_40797015/article/details/112159835