列表中的元素可以是任何类型
l0 = [1, "hello world", ["A", "B", ["C1", "C2", "C3"]], range(10)]
print(l0)
# [1, 'hello world', ['A', 'B', ['C1', 'C2', 'C3']], range(0, 10)]
列表中的列表的索引值是从第一层列表的索引开始到最后一层列表
l0 = [1, "hello world", ["A", "B", ["C1", "C2", "C3"]], range(10)]
print(l0[2])
print(l0[2][2])
print(l0[2][2][2])
# ['A', 'B', ['C1', 'C2', 'C3']]
# ['C1', 'C2', 'C3']
# C3
s0 = "hello world"
l1 = [1, 5, "ok"]
print(list(s0))
print(list(range(10)))
print(list(l1))
# ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [1, 5, 'ok']
int()/float()/bool()/str()
转换内容: 数字、形式为整数的字符串/数字,字符串/任意类型/任意类型
if []:
print("[]为真")
else:
print("[]为假")
# []为假
iterable表示可迭代的,即可拆分的,可使用for循环,如:range()/str/list。
print(l1, id(l1))
l1.append(None)
print(l1, id(l1))
# [1, 5, 'ok'] 1543334029504
# [1, 5, 'ok', None] 1543334029504
s0 = "hello"
print(s0, id(s0))
s0 = "hi"
print(s0, id(s0))
# hello 2686123592880
# hi 2686123593200
for i in range(len(l0)):
print(i, l0[i])
# 0 1
# 1 hello world
# 2 ['A', 'B', ['C1', 'C2', 'C3']]
# 3 range(0, 10)
for e in l0:
print(e)
# 1
# hello world
# ['A', 'B', ['C1', 'C2', 'C3']]
# range(0, 10)
l0 = [1, 2, 3, "hello word", range(5), ["a", "b", "c"], "ok"]
print(l0.append(3.14))
print(l0)
# None
# [1, 2, 3, 'hello word', range(0, 5), ['a', 'b', 'c'], 'ok', 3.14]
l0.insert(2, "python")
print(l0)
# [1, 2, 'python', 3, 'hello word', range(0, 5), ['a', 'b', 'c'], 'ok', 3.14]
l0.extend(range(3))
print(l0)
# [1, 2, 'python', 3, 'hello word', range(0, 5), ['a', 'b', 'c'], 'ok', 3.14, 0, 1, 2]
r = l0.pop()
print(r, l0)
# 2 [1, 2, 'python', 3, 'hello word', range(0, 5), ['a', 'b', 'c'], 'ok', 3.14, 0, 1]
也可定义索引值
r = l0.pop(4)
print(r, l0)
# hello word [1, 2, 'python', 3, range(0, 5), ['a', 'b', 'c'], 'ok', 3.14, 0, 1]
r = l0.remove(3)
print(r, l0)
# None [1, 2, 'python', range(0, 5), ['a', 'b', 'c'], 'ok', 3.14, 0, 1]
l0.clear()
print(l0)
# []
l1 = [1, 2, 3, 3, range(5), [3, "b", "c"], "ok"]
统计元素在列表中出现的次数,并返回;找不出返回0;列表只统计第一层列表。
r = l1.count(7)
a = l1.count(3)
print(r, a)
# 0 2
找出在列表中的下标索引,可指定开始与结束索引;找不出直接报错。
r = l1.index("ok")
print(r)
# 6
逆置列表 没有返回值
r = l1.reverse()
print(r, l1)
# None ['ok', [3, 'b', 'c'], range(0, 5), 3, 3, 2, 1]
l2 = [3, 6, 1, 0, 5]
l3 = [3, 6, 1, 0, 5]
# sort 排序 默认正序
# sort(reverse = True)
l2.sort()
l3.sort(reverse=True)
print(l2)
print(l3)
# [0, 1, 3, 5, 6]
# [6, 5, 3, 1, 0]