Python基础学习【2】-列表简介
2017-10-18 本文已影响29人
爱吃西瓜的番茄酱

一:列表是什么?
1 定义:列表是由一系列按特定顺序排列的元素组成。在Python中,用方括号[]来表示列表,并用逗号来分割其中的元素。
例:

输出:

2 访问列表元素:要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内(记住索引是从0而不是从1开始)
例:

输出:

3 可以通过for循环来遍历列表:
例:

输出:

4 使用列表的各个值:
例:

输出:

二:修改、添加和删除列表
1 修改列表元素:指定列表名和要修改的元素的索引,再指定该元素的新值
例:

输出:

2 在列表末尾添加元素,使用.append()方法
例:

输出:

3 在列表任意位置插入元素,使用.insert()方法
例:

输出:

4 使用del 语句删除元素,可删除列表任意位置的列表元素,条件是知道其索引。
例:

输出:

5 使用.pop()删除元素,可删除列表末尾的元素,并让你能够接着使用它,相当于弹出栈顶元素。
例:

输出:

6 使用.pop()方法弹出列表任意位置的元素,只需在括号内指定要弹出元素的索引。
例:

输出:

7 根据值删除元素,使用.remove()方法
例:

输出:

三 组织列表:
1 使用.sort()方法对列表进行永久性排序(按首字母顺序)
例:

输出:

2 使用函数sorted()对列表进行临时排序
例:

输出:

3 倒着打印列表,使用.reverse()方法
例:

输出:

4 确定列表的长度,使用函数len()
例:

输出:

每天学习一点点,每天进步一点点