zoukankan      html  css  js  c++  java
  • python中容器总结

    python中容器container总结

    首先,什么叫做容器呢?容器顾名思义就是里面可以容纳很多东西,可以理解成已经被包装好的一个盒子。
    python中的container是一种内置的封装好的数据结构,是可以直接拿来使用,不需要自己构造。当然是容器也是可以通过自己构造的。
    本文介绍四种容器:
    列表:List
    集合:set
    字典:dictionary
    元组:tuple

    1. List
      定义:List是一种数组形式的数据结构,但是它可以放置不同类型的基础数据类型,但一般数据类型是相同的
      List是用[ ]括起来的数组元素,可以包含不同的数据类型
    >>>xs = [3, 1, 2]
    >>> print(xs,xs[2])
    [3, 1, 2] 2//可以单个指向
    
    >>> xs[2]='foo'
    >>> print(xs)
    [3, 1, 'foo'] //List可以放置不同数据类型
    
    >>> xs.append('bar')
    >>> print(xs)
    [3, 1, 'foo', 'bar'] //可以添加元素在List尾部
    
    >>> x=xs.pop()
    >>> print(x,xs)
    bar [3, 1, 'foo'] //可以从List尾部pop出元素
    
    print(xs[-1])
    foo
    >>> print(xs[-2])
    1
    >>> print(xs[-3])
    3  //支持反方向获取元素
    

    Slicing:除了一次获取一个元素,List也支持精确的切片处理,能够获取子List

    >>> nums=list(range(6)) //range是一个可以顺序从0产生数字元素的内置函数
    >>> print(nums)
    [0, 1, 2, 3, 4, 5]  //range(i) 产生从0到i-1的List
    >>> print(nums[2:4])
    [2, 3]
    >>> print(nums[2:])
    [2, 3, 4, 5]
    >>> print(nums[:2])
    [0, 1]
    >>> print(nums[:])
    [0, 1, 2, 3, 4, 5]   
    //print(nums[i:j])是打印出从第i个元素(包括第i个)到第j个元素之前(不包括j)的子List
    //如果i为空则默认i=0,从第一个元素开始,j为空则默认获取到最后一个元素(包括进来)
    //i、j都为空则打印整个List
    >>> print(nums[:-1])
    [0, 1, 2, 3, 4]
    >>> nums[2:4]=[8,7]
    >>> print(nums)
    [0, 1, 8, 7, 4, 5]//允许进行切片式修改数据元素
    

    List中的loops循环:

    >>> animals = ['cat', 'dog', 'monkey']
    >>> for animal in animals:
                           print(animal)          
    cat
    dog
    monkey //python中类似for循环语句
    
    animals = ['cat', 'dog', 'monkey']
    for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))
    # Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
     //通过这个enumerate内置函数获取每个元素的index
    

    List中更深一层的使用:我们经常面对的将一个List转化生成另外一种的List,别如:生成数据元素的平方的List

    nums = [0, 1, 2, 3, 4]
    squares = []
    for x in nums:
    squares.append(x ** 2)
    print(squares) # Prints [0, 1, 4, 9, 16]
    

    另一种更简洁的code:

    nums = [0, 1, 2, 3, 4]
    squares = [x ** 2 for x in nums]
    print(squares) # Prints [0, 1, 4, 9, 16]
    

    List参考

    2.Dictionaries
    字典类型存储每个元素是一对数据(a pair),类似于java中的map,其为:隔开的一对一数据构成元素。字典顾名思义,每一个数据项组成为—— 词:对词的解释
    Dictionaries为由{}构成的组合数据类型

    >>> d = {'cat': 'cute', 'dog': 'furry'} //构造一个字典d
    >>> print(d['cat'])//显示‘cat’后的解释,前提为‘cat’存在
    cute
    >>> print('cat'in d) //判断字典中是否有某个词‘cat’
    True
    >>> d['fish'] = 'wet' //往d中
    >>> print(d['fish'])
    wet
    

    loops:可以通过字典中的关键字来实现迭代

    >>> d = {'person': 2, 'cat': 4, 'spider': 8}
    >>> for animal in d:
    	legs = d[animal]
    	print('A %s has %d legs' % (animal, legs))
    
    	
    A cat has 4 legs
    A person has 2 legs
    A spider has 8 legs
    //实现迭代
    

    也可以通过使用item的方法来做到:

    >>> for animal, legs in d.items():
    	print('A %s has %d legs' % (animal, legs))
    A cat has 4 legs
    A person has 2 legs
    A spider has 8 legs//使用.item务必保证key:key value对应
    

    Dictionaries comprehension:
    与List类似,能够允许轻松构建字典类型的数据

    >>> nums = [0, 1, 2, 3, 4]
    >>> even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
    >>> print(even_num_to_square)
    {0: 0, 2: 4, 4: 16}
    

    Dictionary参考

    3.Sets
    Set是一种由{}括起来的内部元素无序放置的序列容器类型。注意与Dictionaries的区分

    >>> animals = {'cat', 'dog'} //定义一个set
    >>> print('cat' in animals)
    True
    >>> print('fish' in animals)
    False
    //判断一个key是否在set中,返回值为bool类型
    
    >>> animals.add('fish')//添加一个key
    >>> print('fish' in animals)
    True
    >>> print(len(animals))
    3
    >>> animals.remove('cat')//移除一个key
    >>> print(len(animals))
    2
    

    Loops:Set的迭代和List有一样的语法,但是鉴于Set是没有顺序的,因此每次显示的结果是不唯一的。

    >>> animals = {'fish', 'Mokey', 'cat'}
    >>> for idx, animal in enumerate(animals):
            print('#%d: %s' % (idx + 1, animal))
    
    #1: Mokey
    #2: fish
    #3: cat
    

    Comprehension:

    >>> from math import sqrt
    >>> nums={ int(sqrt(x))for x in range(30)}
    >>> print(nums)
    {0, 1, 2, 3, 4, 5}
    

    Set参考

    4.tuple多元组
    tuple是由()括起来的多元组,其顺序是不可更改的,且其在很多方面与List类似,但是其与List最大的不同便是tuple可以单独作为Set和Dictionary的元素

    >>> d = {(x, x + 1): x for x in range(10)}//构造字典。key类型为tuple类型
    >>> t = (5, 6)//构造一个tuple
    >>> print(type(t))//类型为tuple
    <class 'tuple'>
    >>> print(d[t])//key为(5,6)的值
    5
    >>> print(d[(1, 2)])
    1
    

    tuple参考

  • 相关阅读:
    每日总结2021.9.14
    jar包下载mvn
    每日总结EL表达语言 JSTL标签
    每日学习总结之数据中台概述
    Server Tomcat v9.0 Server at localhost failed to start
    Server Tomcat v9.0 Server at localhost failed to start(2)
    链表 java
    MVC 中用JS跳转窗体Window.Location.href
    Oracle 关键字
    MVC 配置路由 反复走控制其中的action (int?)
  • 原文地址:https://www.cnblogs.com/zhichao-yan/p/13368518.html
Copyright © 2011-2022 走看看