列表遍历
Pythonic1
2
3
4names = ['juntao', 'xiaojun', 'mingming', 'haohao']
# 查找名字列表中带有字母'm'的名字
m_name = [name for name in names if 'm' in name]
print(m_name)
不要用循环写!1
2
3
4
5m_name = []
for name in names:
if 'm' in name:
m_name.append(name)
print(m_name)
字典遍历
Pythonic1
2
3
4exam_detail = {'juntao': 44, 'xiaojun': 88, 'mingming': 99, 'haohao': 22}
# 找出及格的学生及其分数
score_greater_than_60 = {k: v for k, v in exam_detail.items() if v >= 60}
print(score_greater_than_60)
不要这样写!1
2
3
4
5score_greater_than_60 = {}
for k, v in exam_detail.items():
if v >= 60:
score_greater_than_60[k] = v
print(score_greater_than_60)