标签:dex translate span lis 部分 none 迭代器 创建 pen
通用序列操作:
>>> a = [1,2,3] >>> b = [4,5,6] >>> a + b [1, 2, 3, 4, 5, 6]
>>> ‘hello‘ + ‘world‘
‘helloworld‘
>>> a * 5
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
利用乘法和none可以对列表进行初始化
>>> a = [None] * 10
>>> a
[None, None, None, None, None, None, None, None, None, None]
>>> str = ‘hello‘ >>> ‘h‘ in str True
list:
>>> x=[1,1,1] >>> x[1]=2 >>> x [1, 2, 1]
>>> del x[1] >>> x [1, 1]
>>> x[:]=[4,5,6] >>> x [4, 5, 6]
>>> x.append(5) >>> x [4, 5, 6, 5]
>>> x.count(5)
2
>>> y = [1,2,3] >>> y.extend(x) >>> y [1, 2, 3, 4, 5, 6, 5]
>>> a = [‘hello‘,‘python‘,‘world‘] >>> a.index(‘hello‘) 0
>>> a.insert(0,‘hi‘) >>> a [‘hi‘, ‘hello‘, ‘python‘, ‘world‘]
>>> a [‘hi‘, ‘hello‘, ‘python‘, ‘world‘] >>> a.pop() ‘world‘ >>> a.pop(1) ‘hello‘
>>> a [‘hi‘] >>> a.remove(‘hi‘) >>> a []
>>> a = [1,3,4] >>> a.reverse() >>> a [4, 3, 1]
>>> a [4, 3, 1] >>> a.sort() >>> a [1, 3, 4]
sort方法有两个可选参数,key和reverse,参数key提供一个在排序过程中使用的函数,这个函数为每一个元素创建一个键,所有元素根据键来排序。
>>> x = [‘add‘,‘subl‘,‘hello‘,‘to‘] >>> x.sort(key = len) >>> x [‘to‘, ‘add‘, ‘subl‘, ‘hello‘]
reverse参数为true或是false,用来表明是否要进行反向排序
>>> x.sort(key = len,reverse = True) >>> x [‘hello‘, ‘subl‘, ‘add‘, ‘to‘]
元组:不可变序列
>>> tuple(‘abc‘) (‘a‘, ‘b‘, ‘c‘)
字符串:
>>> ‘hello world‘.find(‘ ‘) 5
>>> str1=‘+‘ >>> str2=[‘1‘,‘2‘,‘3‘] >>> str1.join(str2) ‘1+2+3‘ >>> str2.join(str1) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> str2.join(str1) AttributeError: ‘list‘ object has no attribute ‘join‘
>>> ‘it\‘s a string‘.replace(‘s‘,‘r‘) "it‘r a rtring"
>>> ‘1/2/4/5/6‘.split(‘/‘) [‘1‘, ‘2‘, ‘4‘, ‘5‘, ‘6‘]
>>> ‘ hi ‘.strip() ‘hi‘
>>> ‘ !!!hi!!! ‘.strip(‘ !‘)
‘hi‘
>>> s = ‘hello‘ >>> table = s.maketrans(‘el‘,‘le‘) >>> s.translate(table) ‘hleeo‘
字典:
>>> d {‘name‘: ‘joy‘, ‘age‘: 14} >>> d.clear() >>> d {}
>>> a = {‘name‘:‘admin‘,‘age‘:[1,2,3]} >>> b = a.copy() >>> b[‘name‘] = ‘name‘ >>> b {‘name‘: ‘name‘, ‘age‘: [1, 2, 3]} >>> a {‘name‘: ‘admin‘, ‘age‘: [1, 2, 3]} >>> b[‘age‘].remove(3) >>> a {‘name‘: ‘admin‘, ‘age‘: [1, 2]} >>> b {‘name‘: ‘name‘, ‘age‘: [1, 2]}
深复制
>>> from copy import deepcopy >>> c = deepcopy(b) >>> c {‘name‘: ‘name‘, ‘age‘: [1, 2]} >>> c[‘age‘].remove(1) >>> c {‘name‘: ‘name‘, ‘age‘: [2]} >>> b {‘name‘: ‘name‘, ‘age‘: [1, 2]}
>>> d = {‘name‘:‘a‘,‘age‘:7} >>> d.get(‘name‘) ‘a‘ >>> d.get(‘na‘) >>>
>>> x = d.items() >>> x dict_items([(‘name‘, ‘a‘), (‘age‘, 7)]) >>> list(x) [(‘name‘, ‘a‘), (‘age‘, 7)]
>>> d.keys() dict_keys([‘name‘, ‘age‘])
>>> d.pop(‘age‘) 7 >>> d {‘name‘: ‘a‘} >>>
标签:dex translate span lis 部分 none 迭代器 创建 pen
原文地址:http://www.cnblogs.com/HJhj/p/7399988.html