占用空间小,浪费内存空间少
lis = [1, 2, 3, 1.11] lis = ["a", "b", "c"] lis = [True, False] lis = [{"a": 123}, {"b": 456}] lis = [[1], [2]] lis = [(1), (2)] lis = [1, 1.2, "2", True, {}, [], ()]
# + 运算 a = [1] + [2, 3, ] + [4, 5] print(a) b = [1, 2] + ["3", "4"] print(b) # 输出结果 [1, 2, 3, 4, 5] [1, 2, '3', '4']
# * 运算 a = [1, 2] * 3 print(a) # 输出结果 [1, 2, 1, 2, 1, 2]
# 索引 a = [1, 2, True, {"name": "小菠萝"}, ["how", "hi"]] print(a[0]) print(a[2]) print(a[-1]) print(a[-2]) # 输出结果 1 True ['how', 'hi'] {'name': '小菠萝'}
# 切片 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(a[:]) # 取全部 print(a[0:]) # 取第一个元素到最后一个元素 print(a[::-1]) # 逆序取全部元素 print(a[2:5]) # 取第三个元素到第五个元素 # 输出结果 [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] [0, 9, 8, 7, 6, 5, 4, 3, 2, 1] [3, 4, 5]
注意:赋值的值也必须是列表,否则会报错 TypeError: can only assign an iterable
# 切片赋值 a = ["1", "2", "3"] print(a) a[:] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] # 切片获取所有元素,并重新赋值 print(a) a[2:4] = [33, 44] print(a) a[2:4] = [] # 相当于去掉第 3、4 个元素 print(a) a[:] = [] # 将 a 赋值为空列表 print(a) # 输出结果 ['1', '2', '3'] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] [1, 2, 33, 44, 5, 6, 7, 8, 9, 0] [1, 2, 5, 6, 7, 8, 9, 0] []
# in、not in a = [1, 2, True, {"name": "小菠萝"}, ["how", "hi"]] print(1 in a) print(3 in a) print({"name": "小菠萝"} in a) print(False not in a) # 输出结果 True False True True
获取列表长度
# 获取列表长度 print(len([1, 2, 3, 4])) # 输出结果 4
获取列表值最大的元素
# max a = [1, 2, 3] print(max(a)) # 输出解雇 3
# 其他栗子 a = [1, 2, True, 3] print(max(a)) a = ["a", "b", "c"] print(max(a)) a = [[1, 2], [3, 4], [3, 5]] print(max(a)) # 输出结果 3 c [3, 5]
a = ["a", "b", 1] print(max(a)) # 输出结果 print(max(a)) TypeError: '>' not supported between instances of 'int' and 'str'
上面的栗子都是给 max 函数传递了单个参数
print(max(1, 2, 3)) print(max([1, 2], [1, 2, 3])) # 输出结果 3 [1, 2, 3]
会返回最大的那一个参数值
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
两种传值方式
max(iterable, *[, default=obj, key=func])
倘若只传一个列表,那么可以指定 default 参数值,当传的列表为空的时候,返回 default 值
max(arg1, arg2, *args, *[, key=func])
可以传多个参数,返回最大的参数值
https://www.cnblogs.com/poloyy/p/15058981.html