zoukankan      html  css  js  c++  java
  • 序列(list)

    1.列表、元组和字符串的共同点

    •   都可以通过索引得到每一个元素
    •   默认索引值总是从0开始
    •   可以通过分片的方法得到一个范围内的元素的集合
    •   有很多共同的操作符(重复操作符、拼接操作符、成员关系操作符)

    2.创建序列

    >>> list('abcdefg')
    			 
    ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    >>> list([1,2,3,4,5])
    			 
    [1, 2, 3, 4, 5]
    >>> list(('a',1,5,8,9,6))
    			 
    ['a', 1, 5, 8, 9, 6]
    >>> 
    

    3.重要方法

      len

    >>> len(('a',1,5,8,9,6))
    			 
    6
    >>> 
    

      max,min

    >>> a = ('a',1,5,8,9,6)
    			 
    >>> b = ('3',1,5,8,9,6)
    			 
    >>> max(a)
    			 
    Traceback (most recent call last):
      File "<pyshell#85>", line 1, in <module>
        max(a)
    TypeError: '>' not supported between instances of 'int' and 'str'
    >>> max(b)
    			 
    Traceback (most recent call last):
      File "<pyshell#86>", line 1, in <module>
        max(b)
    TypeError: '>' not supported between instances of 'int' and 'str'
    >>> b = (3,1,5,8,9,6)
    			 
    >>> max(b)
    			 
    9
    >>> 
    

      可以看出在使用max的参数必须是数据类型一致的序列

      sum

    >>> sum(b)
    			 
    32
    
    >>> b = (3,1,5,8,9,6)
    			 
    >>> sum(b,1)
    			 
    33
    

      

      sorted

    >>> b = (3,1,5,8,9,6)
    			 
    >>> sum(b,1)
    			 
    33
    >>> sorted(b)
    			 
    [1, 3, 5, 6, 8, 9]
    >>>
    

      reversed 

    >>> numbers = [1,2,5,6,8,3,8,4]
    			 
    >>> reversed(numbers)
    			 
    <list_reverseiterator object at 0x000001EA6BA17C18>
    >>> 
    

      这样调用是直接返回一个list对象,所以需要用list解析

    <list_reverseiterator object at 0x000001EA6BA17C18>
    >>> list(reversed(numbers))
    			 
    [4, 8, 3, 8, 6, 5, 2, 1]
    >>> 
    

      enumerate 枚举

    >>> enumerate(numbers)
    			 
    <enumerate object at 0x000001EA6BA326C0>
    >>> list(enumerate(numbers))
    			 
    [(0, 1), (1, 2), (2, 5), (3, 6), (4, 8), (5, 3), (6, 8), (7, 4)]
    >>> 
    

      enumerate返回的也是list对象,所以list解析,最终返回一个包含第一个值为索引,第二个值为值的多个元组的列表

      zip

    >>> a = [1,2,3,4,5,6,7,8]
    			 
    >>> b = [5,6,5,4]
    			 
    >>> zip(a,b)
    			 
    <zip object at 0x000001EA6BAB76C8>
    >>> list(zip(a,b))
    			 
    [(1, 5), (2, 6), (3, 5), (4, 4)]
    

      类似男女成对,女生数量不够就会生出很多单身狗^_^

  • 相关阅读:
    Codeforces Gym 100571A A. Cursed Query 离线
    codeforces Gym 100500 J. Bye Bye Russia
    codeforces Gym 100500H H. ICPC Quest 水题
    codeforces Gym 100500H A. Potion of Immortality 简单DP
    Codeforces Gym 100500F Problem F. Door Lock 二分
    codeforces Gym 100500C D.Hall of Fame 排序
    spring data jpa 创建方法名进行简单查询
    Spring集成JPA提示Not an managed type
    hibernate配置文件中的catalog属性
    SonarLint插件的安装与使用
  • 原文地址:https://www.cnblogs.com/xiangdongsheng/p/13415324.html
Copyright © 2011-2022 走看看