列表是python 6种内建序列种最为常见的两种。其实从某种意义上来说,元组是一个不可修改的列表。
列表赋值
列表的各个元素用,
连接,并用[]
框住。
list = [1, 'hello', 1.1]
列表常用方法
元素赋值
列表的索引由0开始,对于单个元素赋值如下。
list = [1, 2, 3, 4]
list[2] = 4
print(list)
# [1, 2, 4, 4]
分片赋值
分片是python的一个强大属性。对于一个列表可以用分片赋值操作,对其进行分割、赋值。
# 对索引3后列表进行赋值
list = [1, 2, 3, 4]
list[3:] = [5, 6]
print(list)
# [1, 2, 3, 5, 6]
# 在索引1的进行赋值
list = [1, 2, 3, 4]
list[1:1] = [5, 6]
print(list)
# [1, 5, 6, 2, 3, 4]
# 删除索引1到3(左含又不含)的数据
list = [1, 2, 3, 4]
list[1:3] = []
print(list)
# [1, 4]
删除元素 & remove
删除元素可以使用del list[index]
的方式,也可以使用remove(value)
的方式,如下。
list = [1, 2, 3, 4]
del list[1]
print(list)
# [1, 3, 4]
list.remove(3)
print(list)
# [1, 4]
+
& extend
列表拼接可以使用+
来完成,也可使用extend()
方法在当前列表后填充一个列表。
list = [1, 2] + [3, 4]
print(list)
# [1, 2, 3, 4]
list.extend([5, 6])
print(list)
# [1, 2, 3, 4, 5, 6]
append
在列表尾部追加一个元素,这个是我最常用的列表操作方式。
list = [1, 2, 3, 4]
list.append('x')
print(list)
# [1, 2, 3, 4, 'x']
index
返回列表中第一个值得索引,如果没有则抛出一个ValueError
list = [1, 2, 3, 4]
print(list.index(1))
# 0
print(list.index(-1))
# ValueError: -1 is not in list
insert
在指定位置插入一个元素
list = [1, 2, 3, 4]
list.insert(2, 'x')
print(list)
# [1, 2, 'x', 3, 4]
pop
pop(index)
会移除列表中某个值,如果不传则默认最后一个。
list = [1, 2, 3, 4]
print(list.pop(2))
# 3
print(list)
# [1, 2, 4]
list.pop()
print(list)
# [1, 2]
sort, sorted, 高级排序
sort()
和sorted()
都是将列表按照默认比较器进行排序。前者是在列表中排序,后者是返回一个排序后的副本,原列表不变。
list = [1, 5, 2, 9]
list.sort()
print(list)
# [1, 2, 5, 9]
list = [1, 5, 2, 9]
list_1 = sorted(list)
print(list)
# [1, 5, 2, 9]
print(list_1)
# [1, 2, 5, 9]
如果你只是想用类中某个成员进行排序,则可以覆写比较器,调用处直接sorted(list)
即可。如下操作,是将一个Param
类列表,按照时间进行排序的操作。
class Param:
def __init__(self, content, date):
self.content = content
self.date = date
# 使用total_ordering修饰器重载 ==, <=, > 运算符
def __eq__(self, other):
return self.date == other.date
def __le__(self, other):
return self.date < other.date
def __gt__(self, other):
return self.date > other.date
元组
元组是不可变得列表,用()
括起来声明。空元祖为()
,多个元素时为(1, 2)
,但只有一个元素时也要加逗号(1,)
。
元组可以通过tuple()
方法将列表转为元组。
list = [1, 2, 3, 4]
print(tuple(list))
# (1, 2, 3, 4)
list2 = [1]
print(tuple(list2))
# (1,)