1.作用
描述多个值,比如爱好
2.定义方式
[]内可以有多个任意类型的值,逗号分隔元素
hobby_list = ['play','swimming','dancing','666']
lt = list('nick')
print(lt)
3.内置方法
## 优先掌握
# 1. 索引取值(正向取值+反向取值),即可存也可取
hobby_list = ['play','swimming','dancing','666']
print(hobby_list[-1])
print(1,hobby_list[-1])
hobby_list[-1] = '233' # 索引修改
print(2,hobby_list[-1])
# 2. 切片
hobby_list = ['play','swimming','dancing','666']
print(hobby_list[:]) # ['play','swimming','dancing','666']
print(hobby_list[::-1]) # 从右到左 # ['666', 'dancing', 'swimming', 'play']
# 3. 长度
hobby_list = ['play','swimming','dancing','666']
print(len(hobby_list))
# 4. 成员运算in/not in
hobby_list = ['play','swimming','dancing','666']
print('play' in hobby_list) # True
# 5. for循环
hobby_list = ['play','swimming','dancing','666']
for hobby in hobby_list:
print(hobby)
# 6. del删除
hobby_list = ['play','swimming','dancing','666']
del hobby_list[-1]
print(hobby_list)
# 7. append() # 追加
hobby_list = ['play','swimming','dancing','666']
hobby_list.append('2333')
print(hobby_list)
## 需要掌握
# count 计数
hobby_list = ['play','swimming','dancing','666']
print(hobby_list.count('666')) # 对列表内的某一个元素计数
# extend 扩展列表
hobby_list = ['play','swimming','dancing','666']
hobby_list.extend([1,2,3,4]) # ctrl+鼠标左键
print(hobby_list)
# clear 清除
hobby_list = ['play','swimming','dancing','666']
hobby_list.clear() # 清除
print(hobby_list)
# copy 复制列表
hobby_list = ['play','swimming','dancing','666']
hobby_list2 = hobby_list.copy() # 复制列表
print(hobby_list2)
hobby_list[-1] = '233'
print(hobby_list)
# pop 删除
hobby_list = ['play','swimming','dancing','666']
hobby_list.pop() # 删除,默认删除最后一个
print(hobby_list)
# index
hobby_list = ['play','swimming','dancing','666',666,'666']
print(hobby_list.index('play')) # 索引2-4内有没有该值
# insert 插入
hobby_list = ['play','swimming','dancing','666']
hobby_list.insert(0,'1') # 插入
print(hobby_list)
# remove 移除
hobby_list.remove('1') # 移除
print(hobby_list)
# reverse 反转
hobby_list = ['play','swimming','dancing','666']
hobby_list.reverse()
print(hobby_list)
# sort 排序(使用sort列表的元素必须是同类型的)
hobby_list = [1,2,43,32,435,234,0]
hobby_list = [['nick', 1000], ['jason', 500000], ['sean', 2000], ['tank', 10000]]
def func(i): # ['nick',1000]
return i[1] # 1000,500000,2000,10000
hobby_list.sort(key=func)
hobby_list.sort(key=lambda i:i[1],reverse=True)
print(hobby_list)
4.存一个值还是多个值
多个值
5.有序还是无序
有序
6.可变or不可变(重点)
可变
lis = [12,]
print(id(lis))
lis.append('12')
print(id(lis))