Python 基础

使用list列表

# 列表
print('list 列表')
classmats = ['one', 'two', 'three']
print(classmats)
# 列表个数
len_list = len(classmats)
print(len_list)
# 获取指定索引的列表值 ,从0开始,-1表示倒数第一个
print(classmats[1])
print(classmats[-1])
# 往列表中追加元素到末尾
classmats.append('four')
print(classmats)
# 可以把元素插入到指定的位置
classmats.insert(1, 'five')
print(classmats)
# 要删除list末尾的元素,用pop()方法: pop(i) 删除指定位置的元素
classmats.pop(1)
print(classmats)

 

使用tuple元组

# tuple 元组 ,tuple一旦初始化就不能修改
print('tuple 元组 ,tuple一旦初始化就不能修改')
tup_mates = (1, 2)
print(tup_mates)

 

使用dict字典

# dict 字典
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print('dict 字典')
print(d['Michael'])
#要避免key不存在的错误,有两种办法,一是通过in判断key是否存在:
print('Thomas' in d)
# 二是通过dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value:
print(d.get('Thomas', -1))
# 要删除一个key,用pop(key)方法,对应的value也会从dict中删除:
d.pop('Bob')

 

使用集合

# set 集合 不存储value,没有重复的key
s = set([1, 2, 3])
# 通过add(key)方法可以添加元素到set中
s.add(4)
# 通过remove(key)方法可以删除元素:
s.remove(4)

 

posted @ 2019-08-28 11:33  斌-逸风  阅读(165)  评论(0编辑  收藏  举报