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

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

 

列表:

  1.列表 的创建

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

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

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

 

    使用[offset]获取元素

 

 

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

 

 

 

    包含列表的列表: 列表可以包含各种类型的元素,包括其他列表

>>> 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]

 

=================================================================

        

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

 

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

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

 

   2、列表操作

   使用[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'}

 

 

 

集合:

  1、使用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}    #集合中的元素是无序的

 

  2、使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值