您的位置:首页 > 编程语言 > Python开发

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

2018-04-01 22:50 561 查看
一、列表
列表可以由零个或多个元素组成,元素之间用逗号分开,整个列表被方括号所包裹。>>> empty_ list = [ ] >>> weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] >>> big_ birds = ['emu', 'ostrich', 'cassowary'] >>> first_ names = ['Graham', 'John', 'Terry', 'Terry', 'Michael']
#也可以使用list()函数来创建一个空列表>>> another_ empty_ list = list() >>> another_ empty_ list [ ]
#使用list()将其他数据类型转换成列表>>> list('cat')['c', 'a', 't']>>> a_tuple = ('ready','fire','aim')>>> list(a_tuple)['ready', 'fire', 'aim']>>> splitme = 'a/b//c/d//e'>>> splitme.split('/')['a', 'b', '', 'c', 'd', '', 'e']
#使用[offset]获取元素 >>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> marxes[ 0] 'Groucho' >>> marxes[ 1] 'Chico' >>> marxes[ 2] 'Harpo'
#包含列表的列表>>> 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[ 0] ['hummingbird', 'finch']
>>> all_ birds[ 1][ 0] 'dodo'
#指定范围并用切片提取元素>>> marxes = ['Groucho', 'Chico,' 'Harpo'] >>> marxes[ 0: 2] ['Groucho', 'Chico']
>>> marxes[:: 2] ['Groucho', 'Harpo']
#使用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']#也可使用+=>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> others = ['Gummo', 'Karl'] >>> marxes += others >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo', 'Gummo', 'Karl']#如果错误的使用append(),那么others会被当成一个单独的元素进行添加,而不是将其中的内容合并>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> others = ['Gummo', 'Karl'] >>> marxes. append( 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] >>> marxes ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo']
#使用remove()删除具有指定值的元素>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo'] >>> marxes. remove(' Gummo') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo']
#使用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判断值是否存在,只要至少出现一次,就返回True>>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> 'Groucho' in marxes True >>> 'Bob' in marxes False
#使用count()记录特定值出现的次数>>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> marxes. count(' Harpo') 1 >>> marxes. count(' Bob') 0 >>> snl_ skit = ['cheeseburger', 'cheeseburger', 'cheeseburger'] >>> snl_ skit. count(' cheeseburger') 3
#使用join()转换为字符串>>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> ', '.join( marxes) 'Groucho, Chico, Harpo'>>> friends = ['Harry', 'Hermione', 'Ron'] >>> separator = ' * ' >>> joined = separator. join( friends) >>> joined 'Harry * Hermione * Ron' >>> separated = joined. split( separator) >>> separated ['Harry', 'Hermione', 'Ron'] >>> separated == friends True
#使用sort()重新排列元素,默认升序,通过添加参数reverse=True可以改变为降序排列#列表方法sort()会对原列表排序,改变原列表内容#通用函数sorted()则会 返回排好序的列表副本,原列表内容不变 >>> marxes = ['Groucho', 'Chico', 'Harpo'] 
>>> sorted_ marxes = sorted( marxes) >>> sorted_ marxes ['Chico', 'Groucho', 'Harpo']
>>> marxes ['Groucho', 'Chico', 'Harpo']
>>> marxes. sort() >>> marxes ['Chico', 'Groucho', 'Harpo']
>>> numbers = [2, 1, 4. 0, 3] >>> numbers. sort( reverse= True) >>> numbers [4. 0, 3, 2, 1]
#使用len()获取长度>>> marxes = ['Groucho', 'Chico', 'Harpo'] <
10495
/span>>>> 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]
#b和a实际上指向同一个对象,因此,无论通过a还是b来 修改列表内容,其结果都会作用于双方>>> b['surprise', 2, 3]
>>> b[0] = 'I hate surprise!'>>> b['I hate surprise!', 2, 3]>>> a['I hate surprise!', 2, 3]
#三种复制方法:    #l列表copy()函数
    #list()转换函数
    #列表分片[:]
>>> a = [1,2,3]>>> b = a.copy()>>> c = list(a)>>> d = a[:]>>> a,b,c,d([1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3])
#注意b、c、d都是a的复制:它们是自身带有值的新对象,与原始的a所指向的列表对象[1,2,3]没有任何关联,改变a不会影响b、c、d的复制:>>> a[ 0] = 'integer lists are boring' >>> a ['integer lists are boring', 2, 3] >>> b [1, 2, 3] >>> c [1, 2, 3] >>> d [1, 2, 3]
二 、元组
元组也是由任意类型元素组成的序列。与列表不同的是,元组是不可变的,这意味着一旦元组被定义,将无法再进行增加、删除或修改元素等操作。因此,元素就像是 一个常量列表。>>> marx_ tuple = 'Groucho', 'Chico', 'Harpo' >>> marx_ tuple ('Groucho', 'Chico', 'Harpo')
可以一口气将元组赋值给多个变量————元组解包>>> marx_ tuple = ('Groucho', 'Chico', 'Harpo') >>> a, b, c = marx_ tuple >>> a 'Groucho' >>> b 'Chico' >>> c 'Harpo'
用tuple()函数 可以将其他类型的数据来创建元组>>> marx_ list = ['Groucho', 'Chico', 'Harpo'] >>> tuple( marx_ list) ('Groucho', 'Chico', 'Harpo')
元组和列表:元组占用空间较小;
你不会意外修改元组的值;
可以将元组用作字典的键;
命名元组;
函数的参数是以元组形式传递的。

三、字典
字典与列表类似,但其中元素的顺序无关紧要,字典是可变的,可以增删改查其中的键值对 。在其他语言中,字典可能会被称作关系型数组、哈希表、或哈希图。字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
可以用dict()将包含双值子序列的序列转换成字典。#包含双值列表的列表>>> lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ] >>> dict( lol){'c': 'd', 'a': 'b', 'e': 'f'}
#包含双值元组的列表>>> 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'}
>>> pythons[' Gilliam'] = 'Terry' >>> pythons {'Cleese': 'John', 'Gilliam': 'Terry', 'Palin': 'Michael', 'Chapman': 'Graham', 'Idle': 'Eric', 'Jones': 'Terry'}
使用update()合并字典,新归入字典的值会取代原有的值>>> others = { 'Marx': 'Groucho', 'Howard': 'Moe' }>>> 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()删除所有元素>>> pythons. clear() >>> pythons { } >>> pythons = { } >>> pythons{ }
使用in判断是否存在>>> pythons = {'Chapman': 'Graham', 'Cleese': 'John', 'Jones': 'Terry', 'Palin': 'Michael'}>>> 'Chapman' in pythonsTrue>>> 'Darren' in pythonsFalse
使用[key]获取元素>>> pythons['Cleese']'John'>>> pythons.get('Cleese','Not a python')'John'>>> pythons.get('Darren','Not a python')'Not a python'
使用keys()获取所有键>>> pythons.keys()dict_keys(['Chapman', 'Cleese', 'Jones', 'Palin'])  #返回的是键的迭代形式,它不需要时间和空间来创建返回的列表。
>>> list(pythons.keys())['Chapman', 'Cleese', 'Jones', 'Palin']
使用values()可以获取字典中的所有值>>> list(pythons.values())['Graham', 'John', 'Terry', 'Michael']
使用items()获取所有键值对>>> list(pythons.items())[('Chapman', 'Graham'), ('Cleese', 'John'), ('Jones', 'Terry'), ('Palin', 'Michael')]
使用=赋值,使用copy()复制————与列表相同,为了避免对字典内容的修改会反映到所有与之相关联的变量名上,可以使用copy()将字典复制到一个新的字典中。
对于列表和元组来说,方括号里的内容是整型的偏移量;对于字典来说,方括号里的是键。它们返回的都是元素的值。
四、集合 
集合就像舍弃了值,仅剩下键的字典一样。键与键之间也不允许重复 。如果你仅仅想知道某一个元素是否存在而不关心其他的,使用集合是个非常好的选择。如果需要为键附加其他信息的话,建议使用字典。
使用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( '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'} ) {'apple', 'cherry', '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(): ...         if 'vodka' in contents: ...              print( name) ... screwdriver martini black russian white russian
>>> for name, contents in drinks. items(): ...          if 'vodka' in contents and not ('vermouth' in contents or 'cream' in contents): ...              print( name) ... screwdriver black russian
合并及运算符    交集运算符&:>>> for name, contents in drinks. items(): ...          if 'vodka' in contents and not contents & {'vermouth', 'cream'}: ...              print( name) ... screwdriver black russian
>>> a = {1,2}>>> b = {2,3}
#交集>>> a & b{2}>>> a.intersection(b){2}
#并集>>> a | b{1, 2, 3}>>> a.union(b){1, 2, 3}
#差集>>> a - b{1}>>> a.difference(b){1}
#异或集(仅在两个集合中出现一次)>>> a ^ b{1, 3}>>> a.symmetric_difference(b){1, 3}
#子集>>> a <= bFalse>>> a.issubset(b)False>>> a <= aTrue
#真子集>>> a < bFalse>>> a < aFalse
#超集>>> a >= bFalse>>> a.issuperset(b)False
#真超集>>> a > bFalse
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: