列表的迭代
num_list = [12, 3, 444, 55,66 ,66, 11, 99.9]
# 可以使用测量列长度
print(len(num_list))
# 1. 遍历(一个一个取出来)
for i in range(len(num_list)):
print(num_list[i]**2)
print("+++++++++++++++++++++++++++++++++++++")
# 2. 第二种 常用的
for x in num_list:
print(x+100)
li = [] # 空列表
for i in range(10):
li.append(i)
print(li)
# 随机列表
from random import randint
score_list = []
for _ in range(10):
score_list.append(randint(40, 100))
print(score_list)
# 选出所有及格的学生
jige_s_list = []
for score in score_list:
if score >= 60:
jige_s_list.append(score)
print("及格的学生有", jige_s_list)
# 选出 score_list中所有偶数分数
ouishu_s_list = []
for score in score_list:
if score %2==0:
ouishu_s_list.append(score)
print("偶数分数的学生有", ouishu_s_list)
列表推导式
from random import randint
# 简化for循环和列表操作
# [表达式 for 临时 in 迭代对象 if 条件]
li = [] # 空列表
for i in range(10):
li.append(i)
print(li)
print([i for i in range(10)])
print([x for x in range(10)])
print([x + 100 for x in range(10)])
print([x**2 for x in range(10)])
print("=================================")
score_list = [randint(20, 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])
列表常见的问题
from random import randint
li = [randint(-20, 20)for _ in range(10)]
print(li)
## 求li 所有元素的和
mySum = 0
for i in li:
mySum += i
print(mySum)
# 2 sum函数
print(sum(li))
# 求li 所有元素最大的值
print(max(li))
maxVal = li[0] # 假设最大的是列表的第一个元素
for num in li:
if num > maxVal:
maxVal = num
print("max = ", maxVal)
元组
# 元组 tuple 和列表很相似, 只是不能修改
a = ('eric', 222, 333, 44.4, [33, 44], (33, 4))
print(a)
print(type(a))
# 访问
print(a[0])
print(a[1])
# 修改
# a[0] = 'haha' # TypeError: 'tuple' object does not support item assignment
# 安全性, 常做函数返回值
# 元组的遍历
for i in a:
print(i)
# 转换
print(list(a))
print(tuple([i for i in range(10)]))
字典
基本操作
# stu_info = ["小鲁班", 18, 1.3, "王者峡谷"]
stu_info = {"name": "小鲁班","age": 18,"height": 1.3, "addr":"王者峡谷"}
print(stu_info)
print(type(stu_info)) # <class 'dict'>
# key - value
# 访问 通过key 得到value
# 字典是自定义索引的列表
print(stu_info['name'])
print(stu_info['age'])
# print(stu_info['gender']) # KeyError: 'gender'
print(stu_info.get("addr"))
print(stu_info.get("gender")) # 如果可以不存在不报错 None
print(stu_info.get("gender", "男")) # 可以设置访问不到的默认值
print(stu_info.get("addr", "草丛中")) #
# 修改
stu_info['age'] = 19
stu_info['age'] = stu_info['age'] + 1
print(stu_info)
# 增加
stu_info['skill'] = "无敌鲨鱼炮"
print(stu_info)
# 存在这个键就是修改, 没有就是增加
# 删除
del stu_info['height']
print(stu_info)