写出pythonic的代码

列表遍历

Pythonic

1
2
3
4
names = ['juntao', 'xiaojun', 'mingming', 'haohao']
# 查找名字列表中带有字母'm'的名字
m_name = [name for name in names if 'm' in name]
print(m_name)

不要用循环写!

1
2
3
4
5
m_name = []
for name in names:
if 'm' in name:
m_name.append(name)
print(m_name)

字典遍历

Pythonic

1
2
3
4
exam_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
5
score_greater_than_60 = {}
for k, v in exam_detail.items():
if v >= 60:
score_greater_than_60[k] = v
print(score_greater_than_60)

参考文章

Donate comment here