• python笔记之列表


    python中列表使用list类关键字,创建一个列表:list1 = [1,2,3,4]使用逗号隔开每个元素,使用方括号包含起来,创建空列表直接使用list2 = []

     1 #!/usr/bin/env python
     2 #-*-coding:utf-8-*-
     3 
     5 
     6 list1 = [1,2,3,4,'5',6]
     7 #列表扩展append在列表末尾增加数据对象
     8 list1.append('7')
     9 print('append扩展后的列表:{0}'.format(list1))
    10 
    11 #列表扩展insert,在列表的指定位置增加数据对象
    12 list1.insert(2,'2') #在第三个位置插入元素'2'
    13 print('insert扩展后的列表:{0}'.format(list1))
    14 
    15 #列表扩展extend,在列表末尾一次性追加另外一个序列中的多个值,这个与append区别,extend扩展后面跟着是另外一个列表
    16 list2 = ['python','java']
    17 list1.extend(list2)
    18 print('extend扩展后的列表:{0}'.format(list1))
    19 
    20 #
    21 print('列表相加:{0}'.format(list1+list2)) #相加,即组合
    22 print('列表乘:{0}'.format(list1*2))  #乘,即复制
    23 
    24 #index索引
    25 print('index索引:{0}'.format(list1.index(2,1,7))) #返回索引位置
    26 
    27 #count计数
    28 print('count索引:{0}'.format(list1.count(1))) #返回统计数量
    29 
    30 #pop 移除,没有加索引位置时默认移除最后一个元素
    31 list1.pop(2) #移除第三个元素
    32 print(list1)
    33 
    34 #remove移除,这个是移除某个元素值,参数为数据对象
    35 list1.remove('5') #移除'5'元素
    36 print(list1)
    37 
    38 #reverse反转
    39 list1.reverse()
    40 print(list1)
    41 
    42 #sort排序
    43 list3 = ['python','c','c++','java']
    44 list3.sort()  #排序要求列表里面元素必须为同一种数据类型
    45 print(list3)
    46 
    47 #列表循环
    48 for i in list1:
    49     print(i)
    50 
    51 #列表推倒式找出list4中大于10的数并放了新列表
    52 list4 = [1,2,4,6,1,44,22,66,1]
    53 list5 = [i for i in  list4 if i>10]
    54 print(list5)

    列表推导式提供了从序列创建列表的简单途径。通常应用程序将一些操作应用于某个序列的每个元素,用其获得的结果作为生成新列表的元素,或者根据确定的判定条件创建子序列。

    每个列表推导式都在 for 之后跟一个表达式,然后有零到多个 for 或 if 子句。返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。

    数据结构

    列表当做堆栈使用,列表方法使得列表可以很方便的作为一个堆栈来使用,堆栈作为特定的数据结构,最先进入的元素最后一个被释放(后进先出)。用 append() 方法可以把一个元素添加到堆栈顶。用不指定索引的 pop() 方法可以把一个元素从堆栈顶释放出来。

    1 list1 = [1,2,3,4,5]
    2 
    3 list1.append(6) #进栈
    4 
    5 list1.pop() #出栈

    使用 del 语句可以从一个列表中依索引而不是值来删除一个元素。这与使用 pop() 返回一个值不同。可以用 del 语句从列表中删除一个切割,或清空整个列表.

    1 list1 = [1,2,3,4,5]
    2 del list1[2:5] #删除2:5列表片段
    3 print(list1)
    4 del list1  #清空列表
  • 相关阅读:
    使用thymeleaf一旦没有闭合标签就会报错怎么解决
    idea中使用thymeleaf标签时有红色的波浪线怎么去掉
    idea创建spring boot+mybatis(oracle)+themeleaf项目
    [React] Understand the React Hook Flow
    [React] Manipulate the DOM with React refs
    [React] Use a lazy initializer with useState
    [Angular] Configure Anuglar CLI to generate inlineTemplate and inlineStyle
    [HTML 5 Performance] Optimize Cross-browser Images with webp and the 'picture' Element
    [HTML 5 Performance] Benchmark functions runtime in chrome console
    [HTML 5 Performance] Measuring used JS heap size in chrome
  • 原文地址:https://www.cnblogs.com/heertong/p/12088490.html
Copyright © 2020-2023  润新知