Python基础(二):列表
学习Python基础语法:https://www.runoob.com/python/python-tutorial.html #生活技巧# #工作学习技巧# #编程学习资源#
文章基于python3撰写,如有错误,欢迎指正。
一、基本概念
列表的格式 定义:变量名 = [变量1, 变量2, 数据1, 数据2]列表可以存放不同数据类型列表可以通过下标切片进行修改my_list = ['The', 'World', '!']
python
运行
1二、常见操作
1.添加元素 append(数据):在列表最后添加一个数据extend(列表):将两个列表合并insert(位置, 数据):将数据添加在指定位置以上操作均会改变列表的值my_list = ["The"] my_list.append('World!')# append,结果为['The', 'World!'] my_list.extend(['muda', 'muda'])# extend,结果为['The', 'World!', 'muda', 'muda'] my_list.insert(0, 'wryyyyy!')# insert,结果为['wryyyyy!'. 'The', 'World!', 'muda', 'muda']
python
运行
1234 2.删除元素 del list[下标]:根据下标删除列表中的元素pop():删除列表最后一位元素remove(数据):根据制定值删除列表中的元素my_list = ['ko', 'no', 'DIO', 'da', '!'] del my_list[0]# del,结果为 ['no','DIO', 'da', '!'] my_list.pop()# pop(),结果为 ['no','DIO', 'da'] my_list.remove('no')# remove(),结果为 ['DIO','da']
python
运行
1234 3.修改元素 my_list[下标] = 新元素:根据下标对列表中的元素进行重新赋值my_list[切片] = 新元素或列表:根据切片对列表中的元素进行重新赋值my_list = ['The', 'World', '!'] my_list[2] = 'wryyyyy!' print(my_list)# 下标修改,结果为['The', 'World', 'wryyyyy!'] my_list[0:2] = ['muda', 'muda', '!'] print(my_list)# 切片修改,结果为['muda', 'muda', '!', 'wryyyyy!']
python
运行
12345 4.查询元素 index(元素):查询元素在列表中出现的位置,存在时返回下标,不存在时报错count(元素):查询元素在列表中出现的次数in:用于判断元素是否出现在列表中,存在时返回Truenot in:用于判断元素是否不出现在列表中,存在时返回Falsemy_list = ['The', 'World!'] print(my_list.index('The'))# index(),结果为0 print(my_list.count('World!'))# count(),结果为1 print('The' in my_list)# in,结果为 True print('wryyyyy!' not in my_list)# not in,结果为 True
python
运行
12345三、内建函数
方法描述list.reverse()逆置列表list.clear()清空列表list.copy()复制列表,浅拷贝list.sort()对列表进行排序,默认升序四、补充内容
待续… 上一篇:Python基础(一):字符串下一篇:Python基础(三):字典网址:Python基础(二):列表 https://www.yuejiaxmz.com/news/view/1386713
相关内容
Python基础:操作列表、切片、元组Python列表
Python 在教育方面的资源列表
零基础 学 python开发 (Genius套餐A) 二十二
python基础===Python 代码优化常见技巧
五种 Python 列表推导式妙用法
Python的基础
Python基础作业
python第二次作业(基础)
Python自学2(列表)

