python 列表相关内容
1、增加
2、修改
3、切片
4、清空
5、删除
6、杂项
#定义两个列表
name2 = [1,2,3,4]
name_list = [‘zhang‘,‘wang‘,‘li‘,‘liu‘,‘yang‘ ,[‘ding‘,‘guo‘],‘zhao‘]
1.列表的追加操作:
name_list.append(name2)
print(name_list)
输出结果:
[‘zhang‘, ‘wang‘, ‘li‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘, [1, 2, 3, 4]]
name2.insert(2,7)
2.列表修改:
name_list[2]=‘WANG‘
print(name_list)
[‘zhang‘, ‘wang‘, ‘WANG‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]
3.列表切片:
秘笈:跟鸵鸟一样,顾首不顾尾
输入:
print(name_list[2:5])
print(name_list[1:-1])
print(name_list[:-2])
print(name_list[2:])
print(name_list[::2])
输出:
[‘zhang‘, ‘wang‘, ‘WANG‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]
[‘WANG‘, ‘liu‘, ‘yang‘]
[‘wang‘, ‘WANG‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘]]
[‘zhang‘, ‘wang‘, ‘WANG‘, ‘liu‘, ‘yang‘]
[‘WANG‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]
[‘zhang‘, ‘WANG‘, ‘yang‘, ‘zhao‘]
4.列表清空:
输入:
name2.clear()
print(name2)
输出结果:
[]
5.列表的删除操作:
1、remove 方法
name_list.remove(‘liu‘)
2、pop 方法
name_list.pop(4)
3、del 方法
del name_list[2]
输入:
name_list.remove(‘liu‘)
print(name_list)
name_list.pop(4)
print(name_list)
del name_list[2]
print(name_list)
输出
[‘zhang‘, ‘wang‘, ‘li‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]
[‘zhang‘, ‘wang‘, ‘li‘, ‘yang‘, ‘zhao‘]
[‘zhang‘, ‘wang‘, ‘yang‘, ‘zhao‘]
6.杂项
判断某一个元素出现的次数:
print(name_list.count(‘li‘))
获取某个给定元素的索引位置:
print(name_list.index(‘yang‘))
列表翻转:
name_list.reverse()
print(name_list)
输出:
[‘zhao‘, [‘ding‘, ‘guo‘], ‘yang‘, ‘liu‘, ‘li‘, ‘wang‘, ‘zhang‘]
列表排序:
输入:
name2.insert(2,6)
print(name2)
name2.sort()
print(name2)
输出:
[1, 2, 6, 3, 4]
[1, 2, 3, 4, 6]
列表拷贝:
name2 = name_list.copy()
print(name2)
输出:
[‘zhang‘, ‘wang‘, ‘li‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]