列表
语法规则
ListName = [成员1,成员2,成员3]
Name = ['A','B','C']
num = [1,2,3]
#遍历列表
print(Name) #结果:['A', 'B', 'C']
#从0开始索引,-1返回最后一个元素
print(Name[0]) #结果:A
print(Name[-1]) #结果:C
#在末尾添加元素
Name.append('D')
print(Name) #结果:['A', 'B', 'C', 'D']
#在特定位置添加元素
Name.insert(0,'First') #结果:['First', 'A', 'B', 'C', 'D']
#删除元素
del Name[0]
print(Name) #结果:['A', 'B', 'C', 'D']
#根据位置删除元素
Name.pop(1)
print(Name) #结果:['A', 'C', 'D']
#根据内容删除元素
Name.remove('A')
print(Name) #结果:['C', 'D']
组织列表
#永久排序
Name = ['D','C','B','A']
Name.sort()
print(Name) #结果:['A', 'B', 'C', 'D']
#临时排序
num = [5,4,3,2,1]
print(sorted(num)) #结果:[1, 2, 3, 4, 5]
print(num) #结果:[5, 4, 3, 2, 1]
#反转列表
Color = ['Red','Yelloe','Blue']
Color.reverse()
print(Color) #结果:['Blue', 'Yelloe', 'Red']
#计算列表长度
number = [1,2,3,4,5,6,7,8,9]
print(len(number)) #结果:9
创建数值列表
#创建数字列表
numbers = list(range(1,10))
print(numbers) #结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
Num = []
for value in range(1,10):
Num.append(value**2)
print(Num) #结果: [1, 4, 9, 16, 25, 36, 49, 64, 81]
#统计计算
print(sum(Num)) #结果:285
print(max(Num)) #结果:81
print(min(Num)) #结果:1
#列表解析
squares = [value**2 for value in range(1,10)]
print(squares) #结果: [1, 4, 9, 16, 25, 36, 49, 64, 81]
使用部分列表
#切片
Num = [1,2,3,4,5,6,7,8,9]
print(Num[0:3]) # 结果:[1, 2, 3]
print(Num[:3]) # 结果:[1, 2, 3]
print(Num[3:]) # 结果:[4, 5, 6, 7, 8, 9]
#遍历切片
for number in Num[0:4]:
print(number)
#结果:
# 1
# 2
# 3
# 4
#复制列表
CopyNum = Num[:]
print(CopyNum) #结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
元组
dimensions = (200,50)
dimensions[0] = 100 #错误:不能修改元组元素
#遍历元组
for dimension in dimensions:
print(dimension)
#结果:
#200
#50
字典
使用字典
# 访问字典
alien01 = {'color':'green','points':5}
print(alien01) # {'color': 'green', 'points': 5}
print(alien01['color']) # green
# 添加键值对应
alien01['x_position'] = 0
alien01['y_position'] = 25
print(alien01) # {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
# 创建空字典
alien02 = {}
alien02['color'] = 'red'
alien02['points'] = 10
print(alien02) # {'color': 'red', 'points': 10}
# 修改字典中的值
print(alien02) # {'color': 'red', 'points': 10}
alien02['color'] = 'blue'
print(alien02) # {'color': 'blue', 'points': 10}
# 删除键值对应
del alien02['points']
print(alien02) # {'color': 'blue'}
# 遍历字典
user01 = {'name':'LTY',
'first':'L',
'last':'TY'}
# 遍历所有键值对应
for a,b in user01.items():
print("\nKey:"+ a)
print("Value:" + b)
# Key:name
# Value:LTY
#
# Key:first
# Value:L
#
# Key:last
# Value:TY
# 遍历所有键
for c in user01.keys():
print("\nKey:" + c)
# Key:name
#
# Key:first
#
# Key:last
# 遍历所有值
for d in user01.values():
print("\nValue:" + d)
# Value:LTY
#
# Value:L
#
# Value:TY