前言
「想要深入了解一下移步至:https://www.yuque.com/docs/share/210e0b26-b09a-4b71-9151-be9519956aff?# 《三元表达式/推导式》」
欢迎私聊或留言其他的用法。这里的卷货,清安(拾贰)
列表推导式简单用法
list_ = [58,59,60,61,89,100,20,30] print(i for i in list_) # <generator object <genexpr> at 0x00000182C9E0A820>
如果单纯这样写,会得到一个生成器。我们改进一下:
list_ = [58,59,60,61,89,100,20,30] print([i for i in list_]) # [58, 59, 60, 61, 89, 100, 20, 30]
这样就能得到结果了,虽然跟原来的没啥区别
列表推导式的小进阶用法
list_ = [58,59,60,61,89,100,20,30] print([i for i in sorted(list_,reverse=False)]) """[20, 30, 58, 59, 60, 61, 89, 100]"""
它等价于如下的写法:
for i in sorted(list_,reverse=False): list1.append(i) print(list1)
简单的字典推导式
b = {"name":"拾贰","age":18,"sex":"男","home":"深圳"} print({keys for keys in b.items()}) # {('age', 18), ('home', '深圳'), ('sex', '男'), ('name', '拾贰')}
它等价于如下写法:
a = set({}) for keys in b.items(): a.add(keys) print(a)
字典推导式的小进阶用法
此处也是群友日常分享的其中一题
students = [ {'name': '小花', 'age': 19, 'score': 90, 'gender': '女', 'tel': '15300022839'}, {'name': '明明', 'age': 20, 'score': 40, 'gender': '男', 'tel': '15300022838'}, {'name': '华仔', 'age': 18, 'score': 90, 'gender': '女', 'tel': '15300022839'}, {'name': '静静', 'age': 16, 'score': 90, 'gender': '不明', 'tel': '15300022428'}, {'name': 'Tom', 'age': 17, 'score': 59, 'gender': '不明', 'tel': '15300022839'}, {'name': 'Bob', 'age': 18, 'score': 90, 'gender': '男', 'tel': '15300022839'} ] lis = {} for i in students: if i['score'] <= 60: lis[i['name']] = i['score'] print(lis) # 等价于 res = {i['name']:i['score'] for i in students if i['score']<=60} print(res) """ {'明明': 40, 'Tom': 59} """
简单的三元表达式
x = 1 y = 2 if x > y: print(x) else: print(y)1
等价于下面的写法
a = 1 b = 2 print(a if a > b else b)