Python推导式简单示例【列表推导式、字典推导式与集合推导式】
本文实例讲述了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列表(list)操作技巧总结》、《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。