4、列表(List)
1)列表和元组都属于序列,可以理解成一种“容器”,收纳了多个数据。
2)序列中包含了元素,元素的位置通过“索引”来确定,和字符串索引类似,第一个索引位置从0开始,第二个为1,以此类推。
3)Python中最常见的两种序列就是列表和元组。
4.1 创建列表
Python 中的列表是将元素用方括号“[]”括起来,元素之间用逗号“,”作间隔的一种数据类型。
# example:
list01 = [1, 2, 3, 4, 5, 6]
list02 = ["How", "do", "you", "do"]
list03 = ['How', 'are', 'you']
list04 = [True, 8, 'Happy']
list05 = [2, 6, [8, 9, 10]]
以上5个列表:
a、list01是有数字构成的一个列表
b、list02和list03是由字符串构成的列表,单引号和双引号发挥的作用都是一样的
c、list04是有不同类型的数据构成的一个list(包括了bool,数值和字符串)
d、list05是由数值和另外一个序列构成了一个list,也就是在一个list中嵌套了另外一个list
4.2、读取列表的值
序列元素的位置索引称为下标(index),Python序列的下标从0开始,即第一个元素对应的下标为0。
# example:
list01 = [1, 2, 3, 4, 5, 6]
list02 = ["How", "do", "you", "do"]
list03 = ['How', 'are', 'you']
list04 = [True, 8, 'Happy']
list05 = [2, 6, [8, 9, 10]]
print('list01[0] = {}'.format(list01[0]))
print('list02[0] = {}'.format(list02[0]))
print('list03[-1] = {}'.format(list03[-1]))
print('list04[0] = {}'.format(list04[0]))
print('list05[0] = {}'.format(list05[0]))
print('list05[2][1] = {}'.format(list05[2][1]))
# 运行结果:
list01[0] = 1
list02[0] = How
list03[-1] = you
list04[0] = True
list05[0] = 2
list05[2][1] = 9
从上面的例子可以看出,list的元素访问跟字符串类似,格式就是list名称[0,1...]。
4.3 更新列表的值
列表是一种可变的序列,可以通过索引赋值等的方式改标列表中的值。
# example:
list01 = [1, 2, 3, 4, 5, 6]
list02 = ["How", "do", "you", "do"]
list03 = ['How', 'are', 'you']
list04 = [True, 8, 'Happy']
list05 = [2, 6, [8, 9, 10]]
list01[2] = 8
list02[0] = 'What'
list03[2] = 'we'
list04[0] = False
list05[0] = 4
list05[2][0] = 7
print('list01 = {}'.format(list01))
print('list02 = {}'.format(list02))
print('list03 = {}'.format(list03))
print('list04 = {}'.format(list04))
print('list05 = {}'.format(list05))
# 运行结果:
list01 = [1, 2, 8, 4, 5, 6]
list02 = ['What', 'do', 'you', 'do']
list03 = ['How', 'are', 'we']
list04 = [False, 8, 'Happy']
list05 = [4, 6, [7, 9, 10]]
4.5 删除列表的值
删除列表中的元素可以使用del命令,格式就是del+列表元素。
list01 = [1, 2, 3, 4, 5, 6]
list02 = ["How", "do", "you", "do"]
list03 = ['How', 'are', 'you']
list04 = [True, 8, 'Happy']
list05 = [2, 6, [8, 9, 10]]
del list01[2]
del list02[0]
del list03[2]
del list04[0]
del list05[2][0]
print('list01 = {}'.format(list01))
print('list02 = {}'.format(list02))
print('list03 = {}'.format(list03))
print('list04 = {}'.format(list04))
print('list05 = {}'.format(list05))
# 运行结果:
list01 = [1, 2, 4, 5, 6]
list02 = ['do', 'you', 'do']
list03 = ['How', 'are']
list04 = [8, 'Happy']
list05 = [2, 6, [9, 10]]
4.6、列表的切片
列表元素的切片和字符串的类似,用法是:列表名[上限:下限:步长]
# example:
list01 = [1, 2, 3, 4, 5, 6]
list02 = ["How", "do", "you", "do"]
list03 = ['How', 'are', 'you']
list04 = [True, 8, 'Happy']
list05 = [2, 6, [8, 9, 10]]
print('list01切片后的效果如下:')
print('list01[0:3] = {}'.format(list01[0:3]))
print('list01[0:4:2] = {}'.format(list01[0:4:2]))
print('list01[1:] = {}'.format(list01[1:]))
print('list01[:-1] = {}'.format(list01[:-1]))
print('list01[-3:-1] = {}'.format(list01[-3:-1]))
# 运行结果:
list01切片后的效果如下:
list01[0:3] = [1, 2, 3]
list01[0:4:2] = [1, 3]
list01[1:] = [2, 3, 4, 5, 6]
list01[:-1] = [1, 2, 3, 4, 5]
list01[-3:-1] = [4, 5]
从上面的结果可以看出,切片的原理和字符串的完全一样,列表切片含头不含尾,比如list01[0:3]输出结果就是[1, 2, 3],只输出了list01[0],list01[1], list01[2]。两个特殊的切片list01[1:]和list01[:-1]可以理解为,前者自索引为1开始一直到列表末尾,这个时候是包括最后一个元素的;后者确定了切片的下限,所以就不包括这个下限,这个下限以前的所有元素都要输出。
4.7、列表的函数与方法
1)列表的函数
a、len():
def len(*args, **kwargs): # real signature unknown
""" Return the number of items in a container. """
pass
def len(*args, **kwargs): # real signature unknown
""" 返回列表中元素的个数。"""
pass
b、max():
def max(*args, key=None): # known special case of max
"""
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty.
With two or more arguments, return the largest argument.
"""
pass
def max(*args, key=None): # known special case of max
"""
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
使用单个可迭代参数,返回其最大的项。默认的关键字参数指定了当提供的iterable为空时返回的对象。
使用两个或多个参数,返回最大的参数。
"""
pass
c、min():
def min(*args, key=None): # known special case of min
"""
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty.
With two or more arguments, return the smallest argument.
"""
pass
def min(*args, key=None): # known special case of min
"""
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
使用单个可迭代参数,返回其最小的项。默认的关键字参数指定了当提供的iterable为空时返回的对象。
对于两个或多个参数,返回最小的参数。
"""
pass
d、list():
def __init__(self, seq=()): # known special case of list.__init__
"""
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.
# (copied from class doc)
"""
pass
def __init__(self, seq=()): # known special case of list.__init__
"""
内置可变序列。
如果没有给出参数,构造函数将创建一个新的空列表。
如果指定,参数必须是可迭代的。
# (copied from class doc)
"""
pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
tuple01 = (1, 2, 3, 4, 5, 6)
print('len(list01) = {}'.format(len(list01)))
print('max(list01) = {}'.format(max(list01)))
print('min(list01) = {}'.format(min(list01)))
print('list(tuple01) = {}'.format(list(tuple01)))
# 运行结果:
len(list01) = 6
max(list01) = 6
min(list01) = 1
list(tuple01) = [1, 2, 3, 4, 5, 6]
2)列表的方法
a、append():
def append(self, *args, **kwargs): # real signature unknown
""" Append object to the end of the list. """
pass
def append(self, *args, **kwargs): # real signature unknown
""" 将对象追加到列表的末尾。"""
pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
list01.append(6)
print('list01.append(6): {}'.format(list01))
list01.append([2,3,4])
print('list01.append([2,3,4]): {}'.format(list01))
# 运行结果:
list01.append(6): [1, 2, 3, 4, 5, 6, 6]
list01.append([2,3,4]): [1, 2, 3, 4, 5, 6, 6, [2, 3, 4]]
b、count()
def count(self, *args, **kwargs): # real signature unknown
""" Return number of occurrences of value. """
pass
def count(self, *args, **kwargs): # real signature unknown
""" 返回值出现的次数。 """
pass
# example:
list01 = [1, 2, 3, 4, 5, 6, 6]
print('list01.count(6) = {}'.format(list01.count(6)))
# 运行结果:
list01.count(6) = 2
c、extend()
def extend(self, *args, **kwargs): # real signature unknown
""" Extend list by appending elements from the iterable. """
pass
def extend(self, *args, **kwargs): # real signature unknown
""" 通过添加来自可迭代对象的元素来扩展列表。 """
pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
list01.extend((2,3,4))
print('list01.extend((2,3,4)): {}'.format(list01))
list01.extend([5,6,7])
print('list01.extend([5,6,7]): {}'.format(list01))
list02 = ["How", "do", "you", "do"]
list01.extend(list02)
print('list01.extend(list02): {}'.format(list01))
# 运行结果:
list01.extend((2,3,4)): [1, 2, 3, 4, 5, 6, 2, 3, 4]
list01.extend([5,6,7]): [1, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 7]
list01.extend(list02): [1, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 7, 'How', 'do', 'you', 'do']
d、index()
def index(self, *args, **kwargs): # real signature unknown
"""
Return first index of value.
Raises ValueError if the value is not present.
"""
pass
def index(self, *args, **kwargs): # real signature unknown
"""
返回第一个值索引。
如果值不存在,则引发ValueError。
"""
pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
print('list01.index(2) = {}'.format(list01.index(2)))
# 运行结果:
list01.index(2) = 1
e、insert()
def insert(self, *args, **kwargs): # real signature unknown
""" Insert object before index. """
pass
def insert(self, *args, **kwargs): # real signature unknown
""" 在索引之前插入对象。"""
pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
list01.insert(2,'Kevin')
print("list01.insert(2,'Kevin'): {}".format(list01))
# 运行结果:
list01.insert(2,'Kevin'): [1, 2, 'Kevin', 3, 4, 5, 6]
f、pop()
def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
"""
pass
def pop(self, *args, **kwargs): # real signature unknown
"""
删除和返回项目在索引(默认的最后)。
如果列表为空或索引超出范围,则引发IndexError。
"""
pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
list01.pop()
print('list01.pop(): {}'.format(list01))
list01.pop(3)
print('list01.pop(3): {}'.format(list01))
# 运行结果:
list01.pop(): [1, 2, 3, 4, 5]
list01.pop(3): [1, 2, 3, 5]
g、remove()
def remove(self, *args, **kwargs): # real signature unknown
"""
Remove first occurrence of value.
Raises ValueError if the value is not present.
"""
pass
def remove(self, *args, **kwargs): # real signature unknown
"""
删除第一个出现的值。
如果值不存在,则引发ValueError。
"""
pass
# example:
list01 = [1, 2, 3, 'Kevin', 4, 5, 6]
list01.remove('Kevin')
print("list01.remove('Kevin'): {}".format(list01))
# 运行结果:
list01.remove('Kevin'): [1, 2, 3, 4, 5, 6]
h、reverse()
def reverse(self, *args, **kwargs): # real signature unknown
""" Reverse *IN PLACE*. """
pass
def reverse(self, *args, **kwargs): # real signature unknown
""" 反转列表中的元素。 """
pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
list01.reverse()
print('list01.reverse(): {}'.format(list01))
# 运行结果:
list01.reverse(): [6, 5, 4, 3, 2, 1]
i、sort()
def sort(self, *args, **kwargs): # real signature unknown
""" Stable sort *IN PLACE*. """
pass
def sort(self, *args, **kwargs): # real signature unknown
""" 对原列表进行排序。 """
pass
# example:
list01 = [6, 5, 4, 3, 2, 1]
list01.sort()
print('list01.sort(): {}'.format(list01))
# 运行结果:
list01.sort(): [1, 2, 3, 4, 5, 6]
j、clear()
def clear(self, *args, **kwargs): # real signature unknown
""" Remove all items from list. """
pass
def clear(self, *args, **kwargs): # real signature unknown
""" 从列表中删除所有项目。"""
pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
list01.clear()
print('list01.clear(): {}'.format(list01))
# 运行结果:
list01.clear(): []
k、copy()
def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of the list. """
pass
def copy(self, *args, **kwargs): # real signature unknown
""" 返回列表的浅拷贝。"""
pass
# example:
list01 = [1, 2, 3, 4, 5, 6]
list02 = list01.copy()
print('list01 = {}'.format(list01))
print('list02 = {}'.format(list02))
print('id(list01) = {}'.format(id(list01)))
print('id(list02) = {}'.format(id(list02)))
# 运行结果:
list01 = [1, 2, 3, 4, 5, 6]
list02 = [1, 2, 3, 4, 5, 6]
id(list01) = 1529877239168
id(list02) = 1529878067648