zoukankan      html  css  js  c++  java
  • python中for...if...构建List

    1.简单的for...[if]...语句

    >>> a=[12, 3, 4, 6, 7, 13, 21]
    >>> newList = [x for x in a]
    >>> newList
    [12, 3, 4, 6, 7, 13, 21]
    >>> newList2 = [x for x in a if x%2==0]
    >>> newList2
    [12, 4, 6]
    

    newList构建了一个与a具有相同元素的List。但是,newList和a是不同的List。执行b=a,b和newList是不同的。

    newList2是从a中选取满足x%2==0的元素组成的List。

    2.嵌套的for...[if]...语句

    嵌套的for...[if]...语句可以从多个List中选择满足if条件的元素组成新的List。下面也举几个例子。

    >>>a=[12, 3, 4, 6, 7, 13, 21]
    >>>b=['a', 'b', 'x']
    >>>newList=[(x, y) for x in a for y in b]
    >>>newList
    [(12, 'a'), (12, 'b'), (12, 'x'), (3, 'a'), (3, 'b'), (3, 'x'), (4, 'a'), (4, 'b'), (4, 'x'), (6, 'a'), (6, 'b'), (6, 'x'), (7, 'a'), (7, 'b'), (7, 'x'), (13, 'a'), (13, 'b'), (13, 'x'), (21, 'a'), (21, 'b'), (21, 'x')]
    >>>newList2=[(x, y) for x in a for y in b if x%2==0 and y<'x']
    >>>newList2
    [(12, 'a'), (12, 'b'), (4, 'a'), (4, 'b'), (6, 'a'), (6, 'b')]
    

      

  • 相关阅读:
    函数特化
    模板函数总结
    学习代码1
    宏指令
    #define宏作用
    oracle 重要函数
    JMeter 系列之—-01 使用
    Selenium系列之--03 常见元素操作总结
    【转】TestNG常用注解
    CMMI 2,3,4,5级涉及的过程域(PA)介绍
  • 原文地址:https://www.cnblogs.com/eniac1946/p/7327144.html
Copyright © 2011-2022 走看看