Tuple
tuple
用小括号或者无括号来表示,是一连串有顺序的数字。
a_tuple = (12,3,5,15,6)
another_tuple = 12,3,5,15,6
print(a_tuple)
print(another_tuple)
"""
(12, 3, 5, 15, 6)
(12, 3, 5, 15, 6)
"""
List
list
是用中括号命名
a_list=[12,3,5,15,6]
print(a_list)
"""
[12, 3, 5, 15, 6]
"""
List 添加
末尾添加
a_list=[12,3,5,15,6]
a_list.append(0) #在 a_list 后追加一个 0
print(a_list)
"""
[12, 3, 5, 15, 6, 0]
"""
指定位置添加
a_list=[12,3,5,15,6]
a_list.insert(1,0) # 在位置1处添加0
print(a_list)
"""
[12, 0, 3, 5, 15, 6, 0]
"""
List 移除
删除项
a_list=[12,3,5,15,6]
a_list.remove(3) # 删除列表中第一个出现的值为 3 的项
print(a_list)
"""
[12, 5, 15, 6]
"""
List 索引
显示特定位置
a_list=[12,3,5,15,6,4,7]
print(a_list[0]) # 显示列表a_list的第0位的值
# 12
print(a_list[-1]) # 显示列表a_list的最末位的值
# 7
print(a_list[0:3]) # 显示列表a_list的从第0位 到 第2位(第3位之前) 的所有项的值
# [12, 3, 5]
print(a_list[5:]) # 显示列表a_list的第5位及以后的所有项的值
# [4, 7]
print(a_list[-3:]) # 显示列表a_list的倒数第3位及以后的所有项的值
# [6, 4, 7]
打印列表中某个值的索引
a_list=[12,3,5,15,6,4,7]
print(a_list.index(3)) # 显示列表a_list中第一次出现的值为3的项的索引
# 1
统计列表中某值出现的次数
a_list=[12,3,5,15,6,4,7,6,6,6]
print(a_list.count(6)) # 统计列表a_list中6出现的次数
# 4
List 排序
a_list=[12,3,5,15,6,4,7,6,6,6]
a_list.sort() # 默认从小到大排序
print(a_list)
# [3, 4, 5, 6, 6, 6, 6, 7, 12, 15]
a_list.sort(reverse=True) # 从大到小排序
print(a_list)
# [15, 12, 7, 6, 6, 6, 6, 5, 4, 3]
两者对比
他们的元素可以一个一个被迭代,输出,运用,定位取值。
list 迭代
for list_item in a_list:
print(list_item)
"""
12
3
5
15
6
"""
tuple 迭代
for tuple_item in a_tuple:
print(tuple_item)
"""
12
3
5
15
6
"""
下一个例子,依次输出 a_tuple
和 a_list
中的各个元素:
for index in range(len(a_list)):
print("index = ", index, ", number in list = ", a_list[index])
"""
index = 0 , number in list = 12
index = 1 , number in list = 3
index = 2 , number in list = 5
index = 3 , number in list = 15
index = 4 , number in list = 6
"""
for index in range(len(a_tuple)):
print("index = ", index, ", number in tuple = ", a_tuple[index])
"""
index = 0 , number in tuple = 12
index = 1 , number in tuple = 3
index = 2 , number in tuple = 5
index = 3 , number in tuple = 15
index = 4 , number in tuple = 6
"""