只有相信自己的目标,努力工作和奋斗的人才能取得最终的成功。但是我一直相信的一件事是,当您触摸自己哭泣时,您就成功了!
本文实例讲述了Python推导式。分享给大家供大家参考,具体如下:
1. 列表推导式
>>> li = [1,2,3,4,5,6] # 求元素的平方 >>> li_a = [x**2 for x in li ] >>> li_a [1, 4, 9, 16, 25, 36] # 提取偶数值 >>> li_b = [x for x in li if x%2==0] >>> li_b [2, 4, 6] # 将多维数组转换成一维数组 >>> li_c = [[1,2], [3], [], [4,5,6]] >>> li_d = [j for i in li_c for j in i ] >>> li_d [1, 2, 3, 4, 5, 6] # 使用map >>> li_1 = ['a', 'b', 'c', 'd'] >>> li_2 = [10, 20, 30, 40] >>> li_e = list(map(lambda x, y:{x:y}, li_1, li_2)) >>> li_e [{'a': 10}, {'b': 20}, {'c': 30}, {'d': 40}]
2. 字典推导式
# 解析列表 >>> li = ['a', 'b', 'c', 'd', 'e'] >>> li_1 = {k:v for k, v in enumerate(li)} >>> li_1 {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'} # 解析字典 >>> dict_a = {'a':10, 'b':20, 'c':30} >>> dict_b = {v:k for k, v in dict_a.items()} >>> dict_b {10: 'a', 20: 'b', 30: 'c'}
3. 集合推导式
>>> set1 = {x for x in range(10)} >>> set1 set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
PS:上述代码在Python2.7与Python3.6环境下测试
希望本文所述对大家Python程序设计有所帮助。
以上就是Python推导式简单示例【列表推导式、字典推导式与集合推导式】。踏出一步又一步,又只能收回一步一步。成长,有些苦涩始终都要去尝。更多关于Python推导式简单示例【列表推导式、字典推导式与集合推导式】请关注haodaima.com其它相关文章!