元组:不可变列表 & 记录
使用help可查看到tuple list的内置属性区别:
T = (1, 2, ‘s1’)
L = [1, 2, ‘s1’]
不可变列表 这一说法,从属性中可以看出,list中与增减改元素的属性,tuple都没有。
元组的内置属性
T.count(value) -> integer
return number of occurrences of value
T.index(value, [start, [stop]]) -> integer
return first index of value.
列表的内置属性
L.append(object) -> None
-- append object to end
L.extend(iterable) -> None
-- extend list by appending elements from the iterable
L.clear() -> None
-- remove all items from L
L.insert(index, object)
-- insert object before index
L.pop([index]) -> item
-- remove and return item at index (default last).
L.remove(value) -> None
-- remove first occurrence of value.
L.reverse()
-- reverse *IN PLACE*
L.sort(key=None, reverse=False) -> None
-- stable sort *IN PLACE*
L.copy() -> list
-- a shallow copy of L
L.count(value) -> integer
-- return number of occurrences of value
L.index(value, [start, [stop]]) -> integer
-- return first index of value.
元组与记录
元组的记录功能,即没有字段,只靠位置索引来记录数据。
因为没有字段,所以正是位置信息给数据赋予了意义,位置不同代表记录的内容不同。
city, year, area = ('Shanghai', 2020, 123.5)
元组拆包 unpacking
将任意可迭代对象,赋值给左侧一个元组。(要求可迭代对象元素个数与左侧元组空挡数一致。)
左侧元组,可使用 * 来忽略多余的元素;使用占位符 _ 来忽略不感兴趣的数据。
a, b = b, a # 不使用中间变量交换两个变量的值
使用 * 将可迭代对象拆包,作为函数的参数
def func(a, b, c):
pass
t = [1, 2, 3]
func( *t )
使用 * 来处理剩余的元素
a, *rest, b, c = range(5)
# a=0, rest=[1, 2], b=3, c=4
# *rest 可出现在任意位置