列表推导式
简化循环和列表的语法操作
格式: [表达式 for 临时变量 in 可迭代对象 if 条件]
from random import randint
# 列表推导式 简化循环和列表的语法操作
# 格式: [表达式 for 临时变量 in 可迭代对象]
print([i for i in range(10)])
print([i**2 for i in range(10)])
print([i for i in "abcde"])
score_list = [randint(40, 100) for _ in range(10)]
print(score_list)
print([score for score in score_list if score>=60])
print([score for score in score_list if score%2==0])
print([score for score in score_list if score%2==1])
列表和函数
from random import randint
score_list = [randint(40, 100) for _ in range(10)]
print(score_list)
# 编写函数求列表中的最大值
def show_max(ls):
# assert 合法的条件, 不合法时返回的提示
assert len(ls) >= 1, "列表不能为空"
max_num = ls[0]
for num in ls:
if num > max_num:
max_num = num
return max_num
print(show_max(score_list))
# 编写函数求列表中的最大值, 并且返回最大值的索引
def show_max2(ls):
# assert 合法的条件, 不合法时返回的提示
assert len(ls) >= 1, "列表不能为空"
max_num, max_index = ls[0], -1
# enumerate 同时返回索引和列表的值
for index, value in enumerate(ls):
if value > max_num:
max_num = value
max_index = index
return max_index, max_num
print(show_max2(score_list))
元组
# tuple 不可以修改的列表
a = (111, "222", "eric", [22, 22], 11.111)
print(a)
print(type(a))
# 访问列表
print(a[0])
print(a[2])
# a[0] = 999 TypeError: 'tuple' object does not support item assignment
# 可以作为函数的返回值,
# 特点: 速度快, 安全
# 遍历
for x in a:
print(x)
# 只有一个元素元组
b = (111, )
print(type(b))
# 空元组
ls = []
print(type(ls))
# z = ()
z = tuple()
print(type(z))
切片
# 切片 : 对序列(sequence)截取一部分的操作 slice
# 对序列(sequence) list string tuple
# 语法 序列名[start: end : step] 左闭右开
name = "Python C++ Java"
ls = [i for i in range(10)]
t = tuple(ls)
print(len(name))
print(name[0:6])
print(name[:6])
print(name[7:10])
print(name[11:15])
print(name[11:])
print(name[:]) # copy
print(name[::1]) # copy
print(name[::2])
print(name[::3])
# -step 代表索引方向为 从右向左
print(name[::-1])
print("abc"[::-1])
print("abcdef"[4::-2])
# 正向索引从零开始, 负向索引从-1开始
print(name[14])
print(name[-1])
print(name[-15]) # P
print(name[-15:-9]) # Python
print(name[-4:]) # Java
print(name[-4::-1]) # J ++C nohtyP
print(name[-6:-9:-1]) # ++c
print(ls[::-1])
print(t[::-1])
#
字典
# 字典 可以自定义索引的列表 无序的
# key - value 数据结构
stu_info = {'name': 'eric', 'age': 19, 'addr': '铁岭的', 11: 666}
print(stu_info)
print(type(stu_info)) #<class 'dict'>
## 访问
# 通过key 访问 value
print(stu_info['name'])
print(stu_info[11])
# print(stu_info['gender']) #KeyError: 'gender'
print(stu_info.get('name'))
print(stu_info.get('gender')) # None
print(stu_info.get('gender', 'male')) # None
print(stu_info.get('age', 18)) # None
print(stu_info.get('score', 0)) # None
# 修改
stu_info['age'] = 33
print(stu_info)
# 增加
stu_info['gender'] = 'male'
print(stu_info)