zoukankan      html  css  js  c++  java
  • python3进阶之推导式2之嵌套列表(list)推导式(comprehensions)

    嵌套列表式,列表中含列表
    示例1:

    # 考虑以下的 3x4 矩阵,如果你想交换行和列,可以用嵌套的列表推导式:
    m1= [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],]
    # 思路:先取每行首位,然后增加列的位置
    m1=[[row[i] for row in m1] for i in range(4)]
    print(m1)
    # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]


    示例2:

    mam = [('x',['open1','open1','open1']),('y',['open1','open1','open0']),('z',['open0','open0','open0'])]

    def find(c):
    # 元组中列表C中的字符串i,遍历i中的字母j,判断j是否为数字,若是则输出
    return [j for i in c for j in i if j.isdigit()]

    na=[w for w, c in mam if find(c) == ['0', '0', '0']]
    print(na)

    示例3:
    # 嵌套列表,找出含有字母“u”两个以上的
    names = [['tom','billy','liubuqun','andrew','liuxiao','steven','liuhu'],['xiaoyunna','xiaoyunwang','xiaoyunyun','sherry','eva']]

    list10=[name for ls in names for name in ls if name.count('u')>=2]
    print(list10)
    # ['liubuqun', 'liuhu', 'xiaoyunyun']


    # for语句实现代码:
    t = []
    for li in names:
    for name in li:
    if name.count('u') >= 2:
    t.append(name)
    print(t)
    # ['liubuqun', 'liuhu', 'xiaoyunyun']
    仙衣眠云碧岚袍,一襟潇洒,两袖飘飘。玉墨舒心春酝瓢,行也逍遥,坐也逍遥。
  • 相关阅读:
    SpringBoot最新教程IDEA版【狂神说Java系列】
    Mybatis最新完整教程IDEA版【通俗易懂2019.11月】
    freemarker 数字格式化(金额格式化)
    idea皮肤插件
    Spring Security 自定义表单登录页
    Spring Security 用户配置
    Spring Security 初体验
    Tomcat 部署 Spring Boot工程
    服务器安装Ngnix
    java读取配置文件
  • 原文地址:https://www.cnblogs.com/max520liuhu/p/8901011.html
Copyright © 2011-2022 走看看