PY基础之列表的内置方法
PY基础之列表的内置方法
1. 作用
描述多个值,比如爱好
2. 定义方式
hobby_list = ['play', 'swimmindeg', 'dancing', '666']
lt = list('nick')
3. 内置方法
hobby = ['play', 'swimming', 'dancing', '666']
hobby[1] = 'rap'
print(hobby) # ['play', 'rap', 'dancing', '666']
print(hobby[::-1]) # ['666', 'dancing', 'rap', 'play']
print(len(hobby)) # 4
print('play' in hobby) # True
for i in hobby:
print(i)
'''
play
rap
dancing
666
'''
del hobby[-1]
print(hobby) # ['play', 'rap', 'dancing']
hobby.append('666')
print(hobby) # ['play', 'rap', 'dancing', '666', '666']
print(hobby.count('666')) # 2
hobby.extend([1,2,3,4])
print(hobby) # ['play', 'rap', 'dancing', '666', '666', 1, 2, 3, 4]
# hobby.clear() # 清除
lt = hobby.copy() # 复制
print(lt)
hobby[-1] = 233
print(hobby) # ['play', 'rap', 'dancing', '666', '666', 1, 2, 3, 233]
print(lt) # ['play', 'rap', 'dancing', '666', '666', 1, 2, 3, 4]
print(hobby.pop()) # 默认删除最后一个元素,并返回该元素
print(hobby.index('play'))
hobby.insert(0,'1') # 在指定位序插入字符
print(hobby)
hobby.remove('1') # 移除指定元素,找不到会报错
print(hobby)
hobby.reverse() # 反转
print(hobby)
hobby1 = [1,2,4,1,3,99,65] # 排序
hobby1.sort()
print(hobby1) # [1, 1, 2, 3, 4, 65, 99]
# 实例,按数字排序
hobby_list = [['nick', 1000], ['jason', 500000], ['sean', 2000], ['tank', 10000]]
def func(i):
return i[1]
hobby_list.sort(key=func)
hobby_list.reverse()
print(hobby_list) # [['jason', 500000], ['tank', 10000], ['sean', 2000], ['nick', 1000]]
4. 存一个值还是多个值
多个值
5. 有序or无序
有序
6. 可变or不可变(重点)
可变