Python 学习笔记(1)Python容器:列表、元组、字典与集合

Python容器:列表、元组、字典与集合html

 

列表:python

  1.列表 的建立数据结构

    使用[ ] 或者 list()建立列表:empty_list = [ ]  或者 empty_list= list()app

    使用list()将其余数据类型转换成列表  方括号[ ]列表 圆括号( )元组函数

        >>> list('cat')         ['c', 'a', 't']

 

    使用[offset]获取元素测试

 

 

    >>> marxes = ['Groucho', 'Chico', 'Harpo']     >>> marxes[0]     'Groucho'

 

 

 

    包含列表的列表: 列表能够包含各类类型的元素,包括其余列表ui

>>> small_birds = ['hummingbird', 'finch'] >>> extinct_birds = ['dodo', 'passenger pigeon', 'Norwegian Blue'] >>> carol_birds = [3, 'French hens', 2, 'turtledoves'] >>> all_birds = [small_birds, extinct_birds, 'macaw', carol_birds]

 

=================================================================lua

        

>>> all_birds [['hummingbird', 'finch'], ['dodo', 'passenger pigeon', 'Norwegian Blue'], 'macaw', [3, 'French hens', 2, 'turtledoves']]

 

        获取列表中字子列表的元素:spa

>>> all_birds[1][0] 'dodo'

 

   二、列表操做code

   使用[offset]修改元素

>>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> marxes[2] = 'Wanda'
>>> marxes ['Groucho', 'Chico', 'Wanda']

 

 

  指定范围并使用切片提取元素

>>> marxes = ['Groucho', 'Chico,' 'Harpo'] >>> marxes[0:2] ['Groucho', 'Chico']

 

 

  使用append()添加元素至尾部

>>> marxes.append('Zeppo') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo']

 

  使用extend()或+=合并列表

  

>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> others = ['Gummo', 'Karl'] >>> marxes.extend(others) >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo', 'Gummo', 'Karl']

 

  使用insert()在指定位置插入元素

  >>> marxes.insert(3, 'Gummo')   >>> marxes   ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo']   >>> marxes.insert(10, 'Karl')   >>> marxes   ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo', 'Karl']

 

  使用del删除指定位置的元素

    del marxes[-1]

 

  使用remove()删除具备指定值的元素

    >>> marxes.remove('Gummo')

 

  使用pop()获取并删除指定位置的元素

  >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo']   >>> marxes.pop()   'Zeppo'
     >>> marxes   ['Groucho', 'Chico', 'Harpo']   >>> marxes.pop(1)   'Chico'
  >>> marxes   ['Groucho', 'Harpo']

 

  使用index()查询具备特定值的元素位置

    >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo']     >>> marxes.index('Chico')     1

 

  使用in判断值是否存在

    >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo']     >>> 'Groucho' in marxes

 

  使用count()记录特定值出现的次数:使用count() 能够记录某一个特定值在列表中出现的次数

      >>> marxes.count('Harpo')

 

  使用join()转换为字符串

      >>> marxes = ['Groucho', 'Chico', 'Harpo']       >>> ', '.join(marxes)       'Groucho, Chico, Harpo'

 

  使用sort()从新排列元素:列表方法sort() 会对原列表进行排序,改变原列表内容;
              通用函数sorted() 则会返回排好序的列表副本,原列表内容不变

    

  使用len()获取长度

    >>> marxes = ['Groucho', 'Chico', 'Harpo']     >>> len(marxes)     3

 

  使用=赋值,使用copy()复制  

    >>> a = [1, 2, 3]     >>> a     [1, 2, 3]     >>> b = a     >>> b     [1, 2, 3]     >>> a[0] = 'surprise'
    >>> a     ['surprise', 2, 3]

 

 

  元组和列表:

  在许多地方均可以用元组代替列表,但元组的方法函数与列表相比要少一些——元组没有
  append()、insert(),等等——由于一旦建立元组便没法修改。既然列表更加灵活,那为
  什么不在全部地方都使用列表呢?缘由以下所示:
    • 元组占用的空间较小
    • 你不会意外修改元组的值
    • 能够将元组用做字典的键(详见3.4 节)
    • 命名元组(详见第6 章“命名元组”小节)能够做为对象的替代
    • 函数的参数是以元组形式传递的

 

字典:

  字典新建:

>>> empty_dict = {}

 

  使用dict() 转换  

>>> lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ] >>> dict(lol) {'c': 'd', 'a': 'b', 'e': 'f'}

  字典中元素的顺序是可有可无的,实际存储顺序可能取决于你添加元
素的顺序。

能够对任何包含双值子序列的序列使用dict(),下面是其余例子。
包含双值元组的列表:

  >>> lot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]   >>> dict(lot)   {'c': 'd', 'a': 'b', 'e': 'f'}

 

  包含双值列表的元组:

  >>> tol = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] )   >>> dict(tol)   {'c': 'd', 'a': 'b', 'e': 'f'}

 

  双字符的字符串组成的列表:

  >>> los = [ 'ab', 'cd', 'ef' ]   >>> dict(los)   {'c': 'd', 'a': 'b', 'e': 'f'}

 

  双字符的字符串组成的元组:

  >>> tos = ( 'ab', 'cd', 'ef' )   >>> dict(tos)   {'c': 'd', 'a': 'b', 'e': 'f'}

   使用[key]添加或修改元素

>>> pythons = { ... 'Chapman': 'Graham', ... 'Cleese': 'John', ... 'Idle': 'Eric', ... 'Jones': 'Terry', ... 'Palin': 'Michael', ... } >>> pythons {'Cleese': 'John', 'Jones': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric'} #使用[KEY]值,添加元素
>>> pythons['Gilliam'] = 'Gerry'
>>> pythons {'Cleese': 'John', 'Gilliam': 'Gerry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'} #使用[KEY]值,修改元素

>>> pythons['Gilliam'] = 'Terry'
>>> pythons {'Cleese': 'John', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'}

使用update()合并字典

>>> pythons = {       #定义一个字典 
... 'Chapman': 'Graham', ... 'Cleese': 'John', ... 'Gilliam': 'Terry', ... 'Idle': 'Eric', ... 'Jones': 'Terry', ... 'Palin': 'Michael', ... } >>> pythons {'Cleese': 'John', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'} #定义另外一个字典 
>>> others = { 'Marx': 'Groucho', 'Howard': 'Moe' } #使用.update(),合并字典
>>> pythons.update(others) >>> pythons {'Cleese': 'John', 'Howard': 'Moe', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Marx': 'Groucho', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'}

 

使用del删除具备指定键的元素

>>> del pythons['Marx']  #删除字典中的元素
>>> pythons {'Cleese': 'John', 'Howard': 'Moe', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'} >>> del pythons['Howard'] >>> pythons {'Cleese': 'John', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'}

 

使用clear()删除全部元素

使用clear(),或者给字典变量从新赋值一个空字典({})能够将字典中全部元素删除:

>>> pythons.clear() >>> pythons {} >>> pythons = {} >>> pythons {}

 

使用in判断是否存在

>>> pythons = {'Chapman': 'Graham', 'Cleese': 'John', 'Jones': 'Terry', 'Palin': 'Michael'} #测试XXX是否在字典中
>>> 'Chapman' in pythons True

 

使用[key]获取元素

>>> pythons['Cleese'] 'John'

 

keys()、values()、items()、=、copy()

使用keys()获取全部键、使用values()获取全部值、使用items()获取全部键值、使用=赋值,使用copy()复制

>>> signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'} >>> signals.keys()     #使用keys()获取全部键
dict_keys(['green', 'yellow', 'red']) >>> list( signals.keys() ) ['green', 'yellow', 'red'] >>> list( signals.values() )#使用values()获取全部值
['go', 'go faster', 'smile for the camera'] >>> list( signals.items() ) #使用items()获取全部键值对
[('green', 'go'), ('yellow', 'go faster'), ('red', 'smile for the camera')] >>> save_signals = signals  #使用=赋值
>>> signals['blue'] = 'confuse everyone'
>>> save_signals {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'} #对字典内容进行的修改会反映到全部与之相关联的变量名上 #================================= # 使用copy()复制
>>> signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'} >>> original_signals = signals.copy() >>> signals['blue'] = 'confuse everyone'
>>> signals {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera', 'blue': 'confuse everyone'} >>> original_signals {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}

 

 

 

集合:

  一、使用set()建立集合

>>> empty_set = set() >>> empty_set set() >>> even_numbers = {0, 2, 4, 6, 8} >>> even_numbers {0, 8, 2, 4, 6} >>> odd_numbers = {1, 3, 5, 7, 9} >>> odd_numbers {9, 3, 1, 5, 7}    #集合中的元素是无序的

 

  二、使用set()将其余类型转换为集合

>>> set( 'letters' ) {'l', 'e', 't', 'r', 's'}  #转换之后,重复的元素会去重

    用列表创建集合:

>>> set( ['Dasher', 'Dancer', 'Prancer', 'Mason-Dixon'] ) {'Dancer', 'Dasher', 'Prancer', 'Mason-Dixon'}

    再试试元组:

>>> set( ('Ummagumma', 'Echoes', 'Atom Heart Mother') ) {'Ummagumma', 'Atom Heart Mother', 'Echoes'}  #使用元组创建集合

    当字典做为参数传入set() 函数时,只有键会被使用:  

>>> set( {'apple': 'red', 'orange': 'orange', 'cherry': 'red'} ) {'cherry', 'apple', 'orange'}

    使用in测试值是否存在    

>>> drinks = { 'martini': {'vodka', 'vermouth'}, 'black russian': {'vodka', 'kahlua'}, 'white russian': {'cream', 'kahlua', 'vodka'}, 'manhattan': {'rye', 'vermouth', 'bitters'}, 'screwdriver': {'orange juice', 'vodka'} } >>> for name, contents in drinks.items():   # 使用IN值测试值是否存在
    if 'vodka' in contents :                        # 使用IN值测试值是否存在

        print(name) martini black russian white russian screwdriver


>>> for name, contents in drinks.items(): if 'vodka' in contents and not ('vermouth' in contents or 'cream' in contents): print(name) black russian screwdriver

合并及运算符

交集运算:&  或者 x.intersection

 

>>> a = {1,2} >>> b = {3,4} >>> a & b set() >>> a.intersection(b) set()

 

异或运算

#使用^ 或者symmetric_difference() 能够得到两个集合的异或集
>>> a ^ b {1, 3} >>> a.symmetric_difference(b) {1, 3} #使用<= 或者issubset() 能够判断一个集合是不是另外一个集合的子集(第一个集合的全部
元素都出如今第二个集合中): >>> a = {1,3} >>> b = {2,4} >>> c = {1} >>> d = {2} >>> a <= b False >>> b <= a False >>> c <= a True >>> c <= b False >>> d <= a False >>> d <= b # 超集与子集正好相反(第二个集合的全部元素都出如今第一个集合中),使用>= 或者
issuperset() 能够进行判断: >>> a >= b False >>> a >= c True >>> a >=d False # 子集 真子集
>>> a > a False >>> a < a False >>> d > d False >>> d < d False >>> d == d True >>> a >= a True >>> d >= d True >>> a <= a True >>> a < a False >>> a > a False

 

 

 

字典与集合:

 用方括号([])建立列表,

使用逗号建立元组(

使用花括号({})建立字典

在每一种类型中,均可以经过方括号对单个元素进行访问:

 

自定义数据结构:

在建立自定义结构的过程当中,惟一的限制来自于内置数据类型自己。

例如:字典的键必须为不可变对象,因此列表、字典以及集合都不能做为字典的键,可是元组能够做为字典的键。

 

 

 

 

 

 

 

    

 

 

 

 

 

 

 

 

 

原文出处:https://www.cnblogs.com/jingle007/p/11127300.html

相关文章
相关标签/搜索