美文网首页
python 推导式

python 推导式

作者: 青铜搬砖工 | 来源:发表于2018-04-05 15:18 被阅读0次

python中可以使用推导式来通过已有的数据序列快速的创建一个数据序列。目前pyhton中有三种推到式。

  • 列表
  • 字典
  • 集合

列表推导式

variable = [元素结果 for i in 已存在的list if 判断条件]

元素结果可以为函数,也可以为表达式,也可以为值。
例如:
输出值:

temp = [i for i in range(30) if i%3==0]
print(temp)//[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

表达式:

temp = [i**2 for i in range(30) if i%3==0]
print(temp)//[0, 9, 36, 81, 144, 225, 324, 441, 576, 729]

函数:

def iii(i):
    i=i**3
    return i
temp = [iii(i) for i in range(30) if i%3==0]
print(temp)//[0, 27, 216, 729, 1728, 3375, 5832, 9261, 13824, 19683]

字典推导式

variable = [k:结果值 for k in 已存在的dict if 判断条件]
variable = [k,v for k,v in 已存在的dict.items() if 判断条件]

输出值:

dict1 = {'a':1,'b':2,'c':3}
temp ={ k:dict1.get(k,0) for k in dict1 if dict1.get(k,0)%3 ==0}
print temp//{'c': 3}

表达式:

dict1 = {'a':1,'b':2,'c':3}
temp ={ k*2:dict1.get(k,0)**2 for k in dict1 if dict1.get(k,0)%3 ==0}
print temp//{'cc': 9}

函数:

def iii(i):
    i=i**3;
    return i
def ii(i):
    i=i*2
    return i
dict1 = {'a':1,'b':2,'c':3}
temp ={ ii(k):iii(dict1.get(k,0)) for k in dict1 if dict1.get(k,0)%3 ==0}
print temp//{'cc': 27}

k,v值互换

dict1 = {'a':1,'b':2,'c':3}
temp ={ v:k for k,v in dict1.items() }
print temp//{1: 'a', 2: 'b', 3: 'c'}

集合

集合推导式与列表相似,只需把[]换成{}
例子

set1 = {1,1,1,2}
temp = {i for i in set1 if i-1>=0}
print(temp)//set([1, 2])

相关文章

  • python推导式

    python的各种推导式(列表推导式、字典推导式、集合推导式) 推导式comprehensions(又称解析式),...

  • 024python的各种推导式

    python的各种推导式(列表推导式、字典推导式、集合推导式) 推导式comprehensions(又称解析式),...

  • Python中各种推导式

    Python的各种推导式(列表推导式,字典推导式,集合推导式) 列表(list)推导式 字典(dict)推导式 集...

  • 列表推导式

    列表推导式 推导式 推导式(又称解析器),是 Python 独有的一种特性。使用推导式可以快速生成列表、元组、字典...

  • Python 推导式

    Python v3.7.0 推导式(comprehensions),是Python的一种独有特性。推导式是可以从一...

  • Python高级用法-推导式

    Python高级用法-推导式 1.什么是推导式 Python推导式是从一个数据集合构建另外一个新的数据结构的语法结...

  • #抬抬小手学Python# 列表推导式与字典推导式

    列表推导式与字典推导式 在 Python 中推导式是一种非常 Pythonic 的知识,本篇博客将为你详细解答列表...

  • python代码简写(推导式 if else for in)

    python代码简写(推导式 if else for in) python中,(x for y in z for ...

  • Python——生成器、列表生成式、迭代器

    Python列表生成式 列表推导式的一般语法 这种语法等价于以下代码 下面举一些列表推导式的栗子: Python中...

  • Python 入门之推导式

    Python 入门之 推导式 推导式就是构建比较有规律的列表,生成器,字典等一种简便的方式 1、推导式 (1)列表...

网友评论

      本文标题:python 推导式

      本文链接:https://www.haomeiwen.com/subject/vitdhftx.html