zoukankan      html  css  js  c++  java
  • Python:列表

    列表:列表是写在方括号([])之间用逗号分隔开的元素列表

    列表创建:

    list1 = list('adb')
    print(type(list1))

    a = ['a','b','c']
    n = [1, 2, 3]
    x = [a,n]
    print(x)

    输出结果:

    <class 'list'>
    [['a', 'b', 'c'], [1, 2, 3]]

    列表访问:

    x = [['a', 'b', 'c'], [1, 2, 3]]
    >>> x[0]
    ['a','b','c']
    
    >>> x[0][1]   #取列表中的列表第1位元素
    'b'

    列表更新:

    >>> list = ['physics', 'chemistry', 1997, 2000]
    >>> list[2] = 2001
    >>> list
    list = ['physics', 'chemistry', 2001, 2000]

    列表内置函数:

    cmp(list1, list2): #比较两个列表的元素

    len(list): #列表元素个数

    max(list): #返回列表元素最大值

    min(list): #返回列表元素最小值

    list(seq): #将元组转换为列表

    列表操作:

    list.append(obj):在列表末尾添加新的对象
    list.count(obj):统计某个元素在列表中出现的次数
    list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
    list.index(obj):从列表中找出某个值第一个匹配项的索引位置
    list.insert(index, obj):将对象插入列表
    list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
    list.remove(obj):移除列表中某个值的第一个匹配项
    list.reverse():反向列表中元素
    list.sort([func]):对原列表进行排序

    举例:

    >>> list = [11,23,11,4342342,11,56,33,23,11,88]
    >>> list
    [11, 23, 11, 4342342, 11, 56, 33, 23, 11, 88]
    >>> list.count(11)    #查看'11'这个对象在列表中出现的次数
    4
    >>> for i in range(list.count(11)):
    list.remove(11)     # 删除列表中为'11'的所有对象
    
    >>> list1
    ['h', 'e', 'l', 'l', 'o']
    >>> list1.extend('12345')  #列表扩展
    >>> list1
    ['h', 'e', 'l', 'l', 'o', '1', '2', '3', '4', '5']
    list1 = [['iphone',5000],['htc',3199],['huawei',3099],['oppo',2999]]
    res = list(enumerate(list1))   #增加序列号
    print(res)
    print(res[1][1][1])

    输出结果:

    [(0, ['iphone', 5000]), (1, ['htc', 3199]), (2, ['huawei', 3099]), (3, ['oppo', 2999])]
    3199

     列表解析:

    动态创建列表,在一个序列的值上应用一个表达式,将其结果收集到一个新的列表中并返回

    语法:list = [expr for val in iterable]

    例:

    >>> list = [x+1 for x in range(10)]
    >>> list
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    对上面例子扩展:

    >>> list = [x+1 for x in range(10)if x > 5]
    >>> list
    [7, 8, 9, 10]

    例:生成一个矩阵

    >>> list = [(x,y,z) for x in range(3) for y in range(3) for z in range(3) ]
    >>> list
    [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2),(0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2),
     (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2),
     (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2),
     (2, 2, 0), (2, 2, 1), (2, 2, 2)]

    例:使用列表解析器统计列表中小于60的个数:

    >>> list1 = [56,66,87,76,78,62,43,12,1]
    >>> list2 = [x for x in list1 if x < 60]
    >>> list2
    [56, 43, 12, 1]
  • 相关阅读:
    Mongodb常用操作(转载)
    java中对象转换工具类,很好用
    IDEA中配置tomcat出现乱码的解决
    小山博客--面试题答案
    Redis简单配置和使用
    线程的控制和线程池
    进程与线程详细解释
    Quartz .Net(定时框架):
    C#面向对象几组关键字的详解(this,base,dynamic,var,const,readonly,is,as)
    C#设计模式--抽象工厂模式(创建型模式)
  • 原文地址:https://www.cnblogs.com/ping-y/p/5826876.html
Copyright © 2011-2022 走看看