python之路-基础篇-六 list和tuple

python之路-基础篇-6 list和tuple

list 列表

Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。

比如,列出班里所有同学的名字,就可以用一个list表示:

classmates = ['Michael', 'Bob', 'Tracy']
print(classmates)

# 输出
# -----------------------------------------------
['Michael', 'Bob', 'Tracy']

 

变量classmates就是一个list。用len()函数可以获得list元素的个数:

print(len(classmates))

# 输出:
# -------------------------------------------------
3

 

用索引来访问list中每一个位置的元素,索引是从0开始的:

print(classmates[0])        # 输出 -->    'Michael'
print(classmates[1])        # 输出 -->    'Bob'
print(classmates[2])        # 输出 -->    'Tracy'
print(classmates[3])
# 输出:
# ------------------------------------------------------------------
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(classmates) - 1

 

如果要取最后一个元素,除了计算索引位置外,还可以用-1做索引,直接获取最后一个元素:

print(classmates[-1])        # 输出 –>   'Tracy'

 

以此类推,可以获取倒数第2个、倒数第3个:

print(classmates[-2])        # 输出 -->     'Bob'
print(classmates[-3])        # 输出 -->     'Michael'

print(classmates[-4])        
# 输出:
# ------------------------------------------------------
raceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

当然,倒数第4个就越界了。

 

在python的世界中,一切皆为对象,每个对象会有一些方法,使用dir(对象名)可以看到都有哪些方法:

python之路-基础篇-六 list和tuple

以下划线开头的都是对象的一些内置方法,我们只需要关心最后面的几个就可以了

 

对象列表常用的方法:

append():在列表末尾添加一个值

python之路-基础篇-六 list和tuple

clear():清空列表中所有的值

python之路-基础篇-六 list和tuple

copy():将该列表拷贝一份赋值给另一个变量

python之路-基础篇-六 list和tuple

count():统计一个给定的值在该列表有多少个元素

python之路-基础篇-六 list和tuple

extend():将2个列表组合,合并为一个列表

python之路-基础篇-六 list和tuple

index():获取一个值在该列表中的位置,如果该值多次存在则返回第一个值的索引

python之路-基础篇-六 list和tuple

insert():在列表的指定位置插入一个值

python之路-基础篇-六 list和tuple

pop():删除列表最后一个元素,并打印这个元素

python之路-基础篇-六 list和tuple

remove():与pop相似,但是这个是删除指定的值,如果该值不存在,则返回一个ValueError的错误信息。

python之路-基础篇-六 list和tuple

reverse():将列表倒序

python之路-基础篇-六 list和tuple

sort():对列表进行排序

python之路-基础篇-六 list和tuple

python之路-基础篇-六 list和tuple

 

 

tuple 元组:

另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改。

tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。

元组与列表的创建方法是相同的,唯一不同的是,当元组只有一个值时,需要这样创建:

python之路-基础篇-六 list和tuple

如果不加逗号,name的值将会是一个字符串:

python之路-基础篇-六 list和tuple

 

元组的方法:

python之路-基础篇-六 list和tuple

元组只有两个方法:count和index

这两个方法的用法跟list是一样的