Python推导式 Python推导式简单示例【列表推导式、字典推导式与集合推导式】
Duke_Nan 人气:0本文实例讲述了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程序设计有所帮助。
加载全部内容