zoukankan      html  css  js  c++  java
  • python 列表生成式

    列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。可以通过一个list推导出另一个list,而代码却十分简洁

    如下面的代码,将列表中的字符串变成小写的,不是字符串的直接输出

    1、循环实现

    L = ['APPLE','BANana',18,'CC']
    L1 = [] #新列表
    
    for i in L:
        if isinstance(i,str): #判断一个变量是不是字符串
            L1.append(i.lower())
        else:
            L1.append(i)
    print(L1)

    2、使用列表生成式实现

    L = ['APPLE','BANana',18,'CC']
    #使用列表生成式将上面list中的字符全部转为小写
    L2=[x.lower() for x in L if isinstance(x,str)] #不是字符串的不会输出
    L2=[x.lower() if isinstance(x,str) else x for x in L]  #生成式需要做if-else判断时,if语句写在中间.
    print(L2)

    特别注意,列表生成式需要if-else判断时,判断语句写在中间

    其他可参考:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/00138681963899940a998c0ace64bb5ad45d1b56b103c48000

  • 相关阅读:
    Redis之主从复制原理
    字符编码
    Android studio报错 "No IDEA annotations attached to the JDK 1.8, some issues will not be found" 解决方法
    json
    ajax
    《人月神话》读后感(三)
    Jquery基础
    EL表达式
    Android Studio更改虚拟机位置
    Mybatis之mybatis的介绍
  • 原文地址:https://www.cnblogs.com/blueteer/p/10057336.html
Copyright © 2011-2022 走看看