这篇文章将为大家详细讲解有关python中有几种推导式,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
1、列表推导式,在一个中括号里包含一个表达式。
old_list = [0,1,2,3,4,5]
new_list = []
for item in old_list:
if item % 2 == 0:
new_list.append(item)
print(new_list)
2、字典推导式,把[]改成了{},并且组成元素有key和value。
old_student_score_info = {
"Jack": {
"chinese": 87,
"math": 92,
"english": 78
},
"Tom": {
"chinese": 92,
"math": 100,
"english": 89
}
}
new_student_score_info = {}
for name, scores in old_student_score_info.items():
if scores["math"] == 100:
new_student_score_info.setdefault(name, scores)
print(new_student_score_info)
3、集合推导式跟使用大括号{},组成元素也只要一个。
old_list = [0, 0, 0, 1, 2, 3]
new_set = {item for item in old_list}
print(new_set)
关于“python中有几种推导式”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。