zoukankan      html  css  js  c++  java
  • 递归遍历列表

     1 # *-* coding: utf-8 *-*
     2 
     3 #列表是可变的,有序的. 列表中可以存放任意混合数据类型
     4 
     5 cast = ["Cleese", "Palin", "Jones", "Idle"]
     6 print(cast)
     7 
     8 #len() 获得列表长度
     9 print(len(cast))
    10 #使用索引方式访问列表, 索引从 0 开始
    11 print(cast[1])
    12 #list.append() 在列表末尾添加一个数据项
    13 cast.append("Gilliam")
    14 #list.pop(index) 从列表末尾删除一个数据项, 不带参数默认最后一个数据项, 返回被删除的数据
    15 print(cast.pop())
    16 #list.extend() 在列表末尾增加一个数据集合
    17 cast.extend(["Gilliam","Chapman"])
    18 #list.remove() 删除列表中指定的数据项
    19 cast.remove("Chapman")
    20 #list.insert() 在指定位置增加数据项, 按索引位置
    21 cast.insert(0, "Chapman")
    22 #isinstance(name, list) , 检查一个对象是否是列表, 返回 True 或 False
    23 print(isinstance(cast, list))
    24 
    25 #遍历列表
    26 for temp in cast:
    27     print(temp)
    28 
    29 count = 0
    30 while count < len(cast):
    31     print(cast[count])
    32     count += 1
    33 
    34 
    35 
    36 
    37 #嵌套列表遍历读取
    38 movies = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91,
    39           ["Graham Chapman", ["Michael Palin", "John Cleese",
    40                               "Terry Gilliam", "Eric Idle", "Terry Jones"]]]
    41 
    42 print(movies)
    43 
    44 for temp1 in movies:
    45 
    46     if isinstance(temp1, list):
    47 
    48         for temp2 in temp1:
    49 
    50             if isinstance(temp2, list):
    51 
    52                 for temp3 in temp2:
    53 
    54                     print(temp3)
    55 
    56             else:
    57 
    58                 print(temp2)
    59 
    60     else:
    61         print(temp1)
    62 
    63 #使用递归解决嵌套列表遍历读取
    64 def print_lol(self, the_list):
    65     for temp in the_list:
    66         if isinstance(temp, list):
    67             print_lol(temp)
    68     else:
    69         print(temp)
    70 
    71 print_lol(movies)
  • 相关阅读:
    CSS让DIV按照背景图片的比例缩放,并让背景图片填充整个元素(转)
    判断浏览器
    $.each遍历json对象
    jq塞入不同状态html的写法 switch (defaults.type)
    vue资料
    第三方登录
    获取一个项目的所有接口
    接口工具调研
    go自动化测试平台
    压测工具 vegeta
  • 原文地址:https://www.cnblogs.com/Roger1227/p/3130325.html
Copyright © 2011-2022 走看看