Python_容器

这里写图片描述
一、序列

所有序列类型都可以进行某些特定的操作。包括:索引、分片、加、乘以及检查某个元素是否属于序列的成员(成员资格)、计算序列长度、找出最大元素和最小元素。

① 索引
numList = [1, 2, 3, 4, 5]
string = 'hello word!'
print numList[3], string[-2]  # 4 d

② 分片
print numList[:3], numList[2:6], numList[:], string[2:-2], string[0:6:2]
# [1,2,3] [3, 4, 5] [1, 2, 3, 4, 5] llo wor hlo

③ 序列相加:只有同类型的序列才能相加
print numList + numList, string + string
# [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] hello word!hello word!

④ 乘法
oneList = [None]
print oneList * 5  # [None, None, None, None, None]    , 可用于初始化列表

⑤ 成员资格
print 'e' in string  # True

⑥ 长度、最小值和最大值
print len(string), max(string), min(numList)  # 11 w 1

1、字符串(不可变序列)

① str 、repr 、反引号:将Python值转换为字符串

print 'hello regan! '+str(56) , 'hello regan! '+repr(56), 'hello regan! '+`56` 
# hello regan! 56

numList = [1,2,3,4,5]
# hello regan! [1, 2, 3, 4, 5]

② 多行字符串的写法

print """ this is a test for
   long string"""
   # 输出的两行字符串间包含换行符以及空格

print 'this is a test for \
   long string'
   # 输出的两行字符串间包含空格

③ r修饰符,字符串原样输出

print 'C:\nowhere'  
    #C:
        owhere
    \n 将被识别为换行符

print r'C:\nowhere' 
    #C:\nowhere
    r 修饰的字符串,所有内容原样输出

④ 字符串格式化与替换

print 'hello %s , welcome to %s !' % ('regan', 'my house')  
# hello regan , welcome to Python !

print 'Pi with three decimals: %.3f' % pi  
# Pi with three decimals: 3.142  
f 格式化浮点数, .3 代表3位小数

# 模板字符串,用于替换指定字符串
from string import Template

s = Template('hello $name')
print s.substitute(name='regan')  
# hello regan

print s.substitute({'name': 'regan'})  
# hello regan

# 如果替换字段是单词的一部分,那么参数名就必须用括号括起来,从而准确指明结尾:
s = Template('re${litter}n')
print s.substitute(litter='ga')  
# regan

# 使用$$插入美元符号
s = Template('i have $$4 !')
# i have $4 !

⑤ 常用方法

# lower()返回小写字符串。upper()返回大写字符串
testString = 'Regan'
print testString.lower()  # regan
print testString.upper()  # REGAN

# find()返回子串所在位置的最左端索引。如果没有找到则返回-1
print testString.find('an')  # 3

# split()切分字符串,返回list
testString = 'www.silence.com.cn'
splitString = testString.split('.')
print splitString  # ['www', 'silence', 'com', 'cn']

# join()传入可迭代对象,返回用特定符号连接的字符串
print '.'.join(splitString)  # www.silence.com.cn

# replace()返回替换了指定子字符串的新字符串
testString0 = testString.replace('c', 'm')
print testString0  # www.silenme.mom.mn

# strip()返回去除两侧(不包括内部)空格的字符串
testString = '  regan    '
print testString.strip()  # regan

2、Unicode字符串
Python中的普通字符串在内部是以8位的ASCII码存储的,而Unicode字符串则存储为16位Unicode字符,这样就能够表示更多的字符集了

print u'字符串'
# 字符串

print u'\n3002'
# 。
以Unicode编码的形式表示

s = '测试'
print type(s)  # <type 'str'>
print len(s)   # 6

b = s.decode('utf8')
print type(b)  # <type 'unicode'>
print len(b)   # 2

3、元组(不可变序列)

① 创建元组
用逗号分割一些值的时候,就自动创建了元组

tp1 = (1,)
tp2 = (1, 2, 3)
tp3 = 1, 2, 3

numList = [1, 2, 3, 4]
print tuple(numList)  # (1, 2, 3, 4)
print tuple('regan')  # ('r', 'e', 'g', 'a', 'n')

② 元组拆包
元组拆包使得一个函数可以用元组的形式返回多个值

def testTuple():
    x = 'regan'
    y = ['r', 'e', 'g', 'a', 'n']
    return (x, y)

# os.path.split() 函数返回以路径和最后一个文件名组成的元组 (path, last_part):
import os
_, filename = os.path.split('/home/luciano/.ssh/idrsa.pub')
print filename  # idrsa.pub
# 拆包时,不总是对元组所有数据都感兴趣,_占位符能帮助处理这种情况。


# 函数用 *args 来获取不确定数量的参数,在平行赋值中,* 前缀只能用在一个变量名前面,但是这个变量可以出现在赋值表达式的任意位置:
# a, *body, c, d = range(5)

③ id() 获取变量的全局id

t = (1, 2, 3)
print id(t)  # 39632728

4、列表(可变序列)

① 创建列表

list1 = []
list2 = [0] * 5
list3 = [1, 2, 3]
list4 = list('hello word!')
print list4  # ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'd', '!']
print ''.join(list4)  # hello word!

② 元素赋值

testList = [1, 2, 3, 4, 5]
testList[2] = 'hello'
print testList  # [1, 2, 'hello', 4, 5]

testList[0:1] = list('regan')
print testList  # ['r', 'e', 'g', 'a', 'n', 2, 'hello', 4, 5]

③ 增加元素

# append()在列表尾部添加一个元素
testList.append(4)
print testList  # ['r', 'e', 'g', 'a', 'n', 'hello', 4, 5, 4]

# extend()在原有列表尾部添加一整个列表的元素
testList0 = [6, 7, 8]
testList.extend(testList0)
print testList  # ['r', 'e', 'g', 'a', 'n', 'hello', 4, 5, 4, 6, 7, 8]
# extend在原有列表基础之上扩展新的列表,而+则是将两个列表连接在一起形成一个新的列表,原列表没有改变。

# insert(x,y)向列表中x索引处插入新元素y
testList.insert(2, 9)
print testList  # ['r', 'e', 9, 'g', 'a', 'n', 'hello', 4, 5, 4, 6, 7, 8]

④ 删除元素

del testList[1]
print testList  # ['r', 'g', 'a', 'n', 2, 'hello', 4, 5]

# pop(x)弹出列表中索引位置为x的元素,不提供x时弹出最后一个元素
testList.pop()
print testList  # ['r', 'e', 9, 'g', 'a', 'n', 'hello', 4, 5, 4, 6, 7]
testList.pop(1)
print testList  # ['r', 9, 'g', 'a', 'n', 'hello', 4, 5, 4, 6, 7]

# remove(x)从列表中删除元素x
testList.remove(4)
print testList  # [9, 'g', 'a', 'n', 'hello', 5, 4, 6, 7]    ,只删除第一个匹配到的元素

④ 常用列表方法

# count(x)返回列表中元素x的个数
print testList.count(4)  # 2

# index(x)返回列表中元素x的索引位置
print testList.index('hello')  # 5

# reversed()将元列表反序,返回一个迭代器
testList1 = [1, 3, 2, 5, 3]
print reversed(testList1)  # <listreverseiterator object at 0x02CCF510>
for x in reversed(testList1):
    print x
print list(reversed(testList1))  # [3, 5, 2, 3, 1]

# sort()将列表排序
testList1.sort()
print testList1  # [1, 2, 3, 3, 5]
testList2 = ['heheh', 'hdaf', 'f', 'fre']
testList2.sort(key=len, reverse=False)   # 根据元素长度从小到大排序
print testList2  # ['f', 'fre', 'hdaf', 'heheh']
testList2.sort(key=len, reverse=True)  # 根据元素从大到小排序
print testList2  # ['heheh', 'hdaf', 'fre', 'f']

⑤ 列表推导

list1 = [str(i) for i in range(2, 10, 1)]]

# 把一个字符串变成 Unicode 码位的列表
codes = [ord(symbol) for symbol in '$¢£¥€¤']
print codes  # [36, 194, 162, 194, 163, 194, 165, 226, 130, 172, 194, 164]

# 通过列表推导求笛卡尔积:
print [x * y for x in [1, 2, 3, 4] for y in [5, 6, 7]]  # [5, 6, 7, 10, 12, 14, 15, 18, 21, 20, 24, 28]

二、映射

  1. 创建字典

    map0 = {}
    map1 = {1: 'regan', 2: 'lucy', 3: 'lily'}
    map2 = dict([(1, 'regan'), (2, 'lucy'), (3, 'lily')])
    map3 = dict(name='regan', age=24)
    
    # fromkeys方法使用给定的键建立新的字典,每个键默认对应的值为None 。
    testMap0 = {}.fromkeys(['name', 'age', 'gender'])
    testMap0 = dict.fromkeys(['name', 'age', 'gender'])
    print testMap0  # {'gender': None, 'age': None, 'name': None}
    
    # 如果不想使用None作为默认值,也可以自己提供默认值。
    testMap0 = dict.fromkeys(['name', 'age', 'gender'], 'unkonwn')
    print testMap0  # {'gender': 'unkonwn', 'age': 'unkonwn', 'name': 'unkonwn'}
    
  2. 获取字典元素个数

    print len(testMap0)  # 3
    
  3. 判断键是否存在

    print 'age' in map3  # True
    
    # has_key方法可以检查字典中是否含有给出的键。表达式d.has_key(k)相当于表达式k in d
    print testMap0.has_key('name')  # True
    
  4. 获取键对应的值

    print testMap0['name']  # unkonwn
    
    # get方法是个更宽松的访问字典项的方法。一般来说,如果试图访问字典中不存在的项时会出错,而用get就不会:
    # 使用get访问一个不存在的键时,没有任何异常,而会得到None值。还可以自定义“默认”值,替换None:
    print testMap0.get('scholl', 'chang`an university')  # chang`an university
    
  5. 为指定键赋值

    map3['name'] = 'lucy'
    
    # setdefault,更新某个键的值,如键不存在则插入
    testMap0.setdefault('age', 24)
    
    # update方法可以利用一个字典项更新另外一个字典
    testMap1 = {'age': 25, 'name': 'regan', 'gender': 'male'}
    testMap0.update(testMap1)
    print testMap0  # {'name': 'regan', 'gender': 'male', 'age': 25}
    
  6. 删除和清空

    del map3['name']
    map3.clear()
    
  7. 遍历字典

    # items方在是将所有的字典项以列表方式返回,这些列表项中的每一项都来自于(键,值)。但是项在返回时并没有特殊的顺序
    print testMap0.items()  # [('gender', 'unkonwn'), ('age', 'unkonwn'), ('name', 'unkonwn')]
    
    # iteritems方法的作用大致相同,但是会返回一个迭代器对象而不是列表:
    print testMap0.iteritems()  # <dictionary-itemiterator object at 0x02B219C0>
    
    # 在很多情况下使用iteritems更高效(尤其是想要迭代结果的情况下)
    # keys方提将字典中的键以列表形式返回,而iterkeys 则返回针对键的迭代器。
    # values方陆以列表的形式返回字典中的值,itervalues返回值的迭代器
    
    # pop方法用来获得对应于给定键的值,然后将这个键值对从字典中移除。
    print testMap0.pop('gender')  # unkonwn
    
    # popitem弹出随机的项,若想一个接一个地移除并处理项,这个方法就非常有效了(因为不用首先获取键的列表)。
    print testMap0.popitem()  # ('age', 'unkonwn')
    
  8. 字典的格式化字符串

    testMap0 = {'name': 'regan', 'age': 24, 'gender': 'male'}
    print 'test map format : %(name)s age is %(age)s' % testMap0  # test map format : regan age is 24
    
  9. 字典推导

    DIAL_CODES = [(62, 'Indonesia'), (55, 'Brazil'), (92, 'Pakistan'), (880, 'Bangladesh'), (234, 'Nigeria'), (7, 'Russia'), (81, 'Japan')]
    
    country_code = {country: code for code, country in DIAL_CODES}
    
    print {code: country.upper() for country, code in country_code.items() if code < 66}
    # {7: 'RUSSIA', 62: 'INDONESIA', 55: 'BRAZIL'}
    
  10. 复制
    copy方法返回一个具有相同键值对的新字典(这个方法实现的是浅复制)

    testMap0 = {'name': 'regan', 'age': 24, 'gender': 'male'}
    testMap1 = testMap0.copy()
    print testMap1  # {'gender': 'male', 'age': 24, 'name': 'regan'}
    
    # 深复制(deep copy )
    from copy import deepcopy
    
    testMap2 = deepcopy(testMap1)
    print testMap2  # {'gender': 'male', 'age': 24, 'name': 'regan'}
    
  11. 对序列元素进行计数并以字典形式返回

    from collections import Counter
    
    ct = Counter('abracadabra')
    print ct  # Counter({'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1})
    print ct.most_common(2)  # [('a', 5), ('r', 2)] ,返回计数最大的前两个元素
    
  12. 对字典元素进行排序

    d = {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}
    print sorted(d.iteritems(), key=lambda x: x[1], reverse=True)  # [('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)]
    

    三、集合

    集合是由序列(或者其他可选代的对象)构建的,集合内的元素都是唯一不重复的。和字典一样,集合元素的顺序是随意的。

    ① 创建集合

    s1 = set()
    s2 = set([1, 2, 2, 4, 2, 3])
    

    ② 集合是可变的,所以不能用做字典中的键。集合本身只能包含不可变(可散列的)值,所以也就不能包含其他集合。

    # 散列值
    testHash = 'this is s test'
    print hash(testHash)  # 735227663
    
    # 特例:frozenset类型,用于代表不可变(可散列)的集合,此集合可以嵌套在其他集合内部。
    a = set()
    b = set()
    a.add(frozenset(b))
    
    # frozenset构造函数创建给定集合的副本,不管是将集合作为其他集合成员还是字典的键, frozenset都很有用。
    print frozenset(range(10))  # frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    

    ③ 集合推导

    testSet = {chr(i) for i in range(32, 256)}
    

    ④ 集合常用方法

    testSet.add(1)
    testSet.pop()
    testSet.remove(1)
    testSet.clear()
    

    ⑤ 集合数学方法

    a = set([1, 2, 3])
    b = set([2, 3, 4, 5])
    print a.union(b)  # set([1, 2, 3, 4, 5])
    print a | b  # set([1, 2, 3, 4, 5])
    print b.issubset(a)  # False
    print b >= a  # False
    print a.intersection(b)  # set([2, 3])
    print a.difference(b)  # set([1])
    print a - b  # set([1])
    print a.symmetric_difference(b)  # set([1, 4, 5])
    print a ^ b  # set([1, 4, 5])
    print a.copy()  # set([1, 2, 3])
    print a.copy() is a  # False
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值