`

Python 列表、元组、字符串、字典方法汇总

 
阅读更多

学习python也有一段时间了,可是对于python应用还得多多练习方可。

这里记录下对应学习的方法,便于以后查找。

 

  • 列表方法
  • 元组方法
  • 字符串方法
  • 字典方法

一、列表方法

 

list函数用于把序列转换成列表

 

  1. append
  2. count
  3. extend
  4. index
  5. insert
  6. pop
  7. remove
  8. reverse
  9. sort
  10. 高级排序

1.append

append方法用于在列表末尾追加新的对象

>>> lst = [1,2,3]
>>> lst
[1, 2, 3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

append方法是直接修改对象的值

 

 

2.count

count方法用于统计某个元素在列表中出现的次数

>>> lst = [1,5,5,4,4,3,5,[1,2,3],[1,2,[1,2,3]]]
>>> lst
[1, 5, 5, 4, 4, 3, 5, [1, 2, 3], [1, 2, [1, 2, 3]]]
>>> lst.count(1)
1
>>> lst.count([1,2,3])
1
>>> lst.count(5)
3
>>> lst.count(3)
1

 

 

3.extend

extend方法可以在列表的末尾一次性追加另一个序列的多个值

>>> a = [1,2,3]
>>> a
[1, 2, 3]
>>> b = [4,5,6]
>>> b
[4, 5, 6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
>>> b
[4, 5, 6]


extend不同于"+"连接符,"+"连接符不会改变原始值

 

 

4.index

index方法用于从列表中找出某个值第一个匹配项的索引位置

>>> lst = list("what is your name")
>>> lst
['w', 'h', 'a', 't', ' ', 'i', 's', ' ', 'y', 'o', 'u', 'r', ' ', 'n', 'a', 'm', 'e']
>>> lst.index("w")
0
>>> lst.index("a")
2
>>> lst.index("a",3)
14

 隐性参数",3"可以指定查找的起始位置

 

 

5.insert

insert方法用于将对象插入到列表中

>>> a = range(1,7)
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.insert(3,'lol')
>>> a
[1, 2, 3, 'lol', 4, 5, 6]
>>> a[3]

 可指定插入后的索引位置

 

 

6.pop

pop方法会移除列表中的一个元素(默认是最后一个),并且返回该元素的值

>>> x = range(1,4)
>>> x
[1, 2, 3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]

 可给予pop参数索引位置,删除指定元素

 

 

7.remove

remove方法用于移除列表中的某个值的第一个匹配项

>>> x = ['to','be','number','one','to','be','number','one']
>>> x
['to', 'be', 'number', 'one', 'to', 'be', 'number', 'one']
>>> x.remove('to')
>>> x
['be', 'number', 'one', 'to', 'be', 'number', 'one']

 

 

8.reverse

reverse方法将列表中的元素反向存放

>>> x = range(1,11)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> x.reverse()
>>> x
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

 

 

9.sort

sort方法用于在原位置对列表进行排序

x[:]得到包含所有元素的分片,这是一种很有效率的复制整个列表的方法

>>> x = [5,4,3,6,7,1]
>>> x.sort()
>>> x
[1, 3, 4, 5, 6, 7]

 

 

10.高级排序

 

飞船操作符

>>> cmp(1,2)
-1
>>> cmp(2,1)
1
>>> cmp(1,1)
0

 

 

>>> number = [5,2,9,7]
>>> number
[5, 2, 9, 7]
>>> number.sort(cmp)
>>> number
[2, 5, 7, 9]
>>> number = [5,2,9,7]
>>> number
[5, 2, 9, 7]
>>> number.sort()
>>> number
[2, 5, 7, 9]

 

 

可通过sort方法的可选参数key和reverse来自定义排序

>>> x = ['aaaaa','aaaaa','aaa','aa','a']
>>> x
['aaaaa', 'aaaaa', 'aaa', 'aa', 'a']
>>> x.sort(key=len)
>>> x
['a', 'aa', 'aaa', 'aaaaa', 'aaaaa']
>>> x = ['4','6','2','1','9']
>>> x
['4', '6', '2', '1', '9']
>>> x.sort(reverse=True)
>>> x
['9', '6', '4', '2', '1']

 

 

 

二、元组方法

 

tunple函数用于把序列转换成元组

 

元组除了创建元组和访问元组之外没有什么太多操作

>>> x = 1,2,3
>>> x
(1, 2, 3)
>>> x[1]
2
>>> x[:2]
(1, 2)

 

 

 

三、字符串方法

 

  1. find
  2. join
  3. lower
  4. replace
  5. split
  6. strip
  7. translate

1.find

find方法可以在一个较长的字符串中查找字符串,它返回子串所在位置的最左端索引。如果没有找到则返回-1

>>> strings = ("whith a moo-moo here, and a moo-moo threr")
>>> strings
'whith a moo-moo here, and a moo-moo threr'
>>> strings.find('moo-moo')
8
>>> strings.find('whith')
0
>>> strings.find('FLy')
-1
>>> strings.find('moo-moo',8)
8
>>> strings.find('moo-moo',9)
28
>>> strings.find('moo-moo',9,27)
-1

 隐性参数,可指定起始索引值、结束索引值。

 

 

2.join

join方法用于在队列中添加元素

>>> number = ['1','2','3','4','5','6']
>>> seq = '+'
>>> seq.join(number)
'1+2+3+4+5+6'

 

 

3.lower

lower方法返回字符串的小写字母版

>>> strings = 'Nice To Meet You'
>>> strings
'Nice To Meet You'
>>> strings.lower()
'nice to meet you'

 

 

4.replace

replace方法返回某字符串的所有匹配项均被替换后之后得到的字符串

>>> strings = "This is a test print"
>>> strings
'This is a test print'
>>> strings.replace('print','lol')
'This is a test lol'

 

 

5.split

split方法用于将字符串分割成序列

>>> strings = '1+2+3+4+5+6'
>>> strings.split('+')
['1', '2', '3', '4', '5', '6']
>>> list = strings.split('+')
>>> list
['1', '2', '3', '4', '5', '6']

 

 

6.strip

strip返回去除两侧特殊字符串(默认空格)

>>> strings = '   Is this your handbag?             '
>>> strings
'   Is this your handbag?             '
>>> strings.strip()
'Is this your handbag?'
>>> strings
'   Is this your handbag?             '
>>> strings = '++++Is this your handbag    !!!!!!!*******+++++'
>>> strings
'++++Is this your handbag    !!!!!!!*******+++++'
>>> strings.strip('+!* ')
'Is this your handbag'

 可去除指定的特殊字符,注意只是两侧的

 

 

7.translate

translate方法和replace方法一样,可以替换字符串中的某些位置,可是可以同时进行多个替换。注意:需要转换表

>>> from string import maketrans
>>> table = maketrans('A','B')
>>> strings = 'A is happiness'
>>> strings.translate(table)
'B is happiness'
>>> strings
'A is happiness'

 

 

 

四、字典方法

 

dict函数可以通过其他映射或者(键->值)这样的序列建立字典

>>> string = [("A","1"),("B","2")]
>>> string
[('A', '1'), ('B', '2')]
>>> d = dict(string)
>>> d
{'A': '1', 'B': '2'}

 

 

也可以通过关键字参数来创建字典

>>> d = dict(name='yumeng',age='20')
>>> d
{'age': '20', 'name': 'yumeng'}

 

 

  1. clear
  2. copy
  3. fromkeys
  4. get
  5. has_key
  6. items
  7. iteritems
  8. keys
  9. iterkeys
  10. pop
  11. popitem
  12. setdefault
  13. update
  14. values
  15. itervalues

1.clear

clear方法用于清除字典中所有的项

>>> d = {}
>>> d['name'] = 'yumeng'
>>> d['age'] = '20'
>>> d
{'age': '20', 'name': 'yumeng'}
>>> strings = d.clear()
>>> strings
>>> d
{}
>>> print strings
None

 

 

2.copy

copy用于返回一个具有相同键-值对的新字典(浅复制)

>>> x = {'username':'admin','machice':['foo','bar','baz']}
>>> x
{'username': 'admin', 'machice': ['foo', 'bar', 'baz']}
>>> y = x.copy()
>>> y
{'username': 'admin', 'machice': ['foo', 'bar', 'baz']}
>>> y['username'] = 'yumeng'
>>> y['machice'].remove('bar')
>>> y
{'username': 'yumeng', 'machice': ['foo', 'baz']}
>>> x
{'username': 'admin', 'machice': ['foo', 'baz']}

 

 

当副本y替换值的时候原始字典不受影响,但是修改了某个值,原始字典也会改变,为了避免这个问题,那么之用deepcopy函数的深复制

>>> from copy import deepcopy
>>> d = {}
>>> d['name'] = ['A','B']
>>> d
{'name': ['A', 'B']}
>>> c = d.copy()
>>> cc = deepcopy(d)
>>> d['name'].append('C')
>>> c
{'name': ['A', 'B', 'C']}
>>> cc
{'name': ['A', 'B']}

 

 

3.fromkeys

fromkey方法是用给定的键建立新的字典,每个键默认对应的值为None。

>>> {}.fromkeys(['name','age'])
{'age': None, 'name': None}
>>> {}.fromkeys(['name','age'],'yumeng')
{'age': 'yumeng', 'name': 'yumeng'}

 可以指定默认值

 

 

4.get

get方法适用于访问字典项,不过很宽松

>>> d = {}
>>> print d['name']

Traceback (most recent call last):
  File "<pyshell#331>", line 1, in <module>
    print d['name']
KeyError: 'name'
>>> print d.get('name')
None
>>> print d.get('name','没有这个值')
没有这个值
>>> 

 

是用get访问字典,就算没有这个值不会报错,也可以指定这个报错信息。

 

5.has_key

has_key方法可以检查字典中是否含有给出的键

>>> d = {}
>>> d.has_key('yumeng')
False
>>> d['yumeng'] = 'good'
>>> d.has_key('yumeng')
True

 

 

6.items

tiems方法用于将所有的字典项以列表的方式返回

>>> d = {}
>>> d['name'] = 'yumeng'
>>> d['age'] = '20'
>>> d
{'age': '20', 'name': 'yumeng'}
>>> d.items()
[('age', '20'), ('name', 'yumeng')]

 

 

7.iteritems

iteritems方法用于将所有字典项以迭代器的方式返回

>>> d = {}
>>> d['name'] = 'yumeng'
>>> d['age'] = '20'
>>> d
{'age': '20', 'name': 'yumeng'}
>>> d.iteritems()
<dictionary-itemiterator object at 0x01EEB930>

 

 

8.keys

keys方法用于将字典中的键以列表形式返回

>>> d = {}
>>> d['name'] = 'yumeng'
>>> d['age'] = '20'
>>> d
{'age': '20', 'name': 'yumeng'}
>>> d.keys()
['age', 'name']

 

 

9.iterkeys

iterkeys方法用于将字典中的键以迭代器的形式返回

>>> d = {}
>>> d['name'] = 'yumeng'
>>> d['age'] = '20'
>>> d
{'age': '20', 'name': 'yumeng'}
>>> d.iterkeys()
<dictionary-keyiterator object at 0x01EEB930>

 

 

10.pop

pop方法用于获得对应于给定键的值,然后将这个项删除。

>>> d = {'x':1,'y':2}
>>> d
{'y': 2, 'x': 1}
>>> d.pop('x')
1
>>> d
{'y': 2}

 

 

11.popitem

popitem方法用于随机删除字典中的项,并返回这个项的值

>>> d
{'y': 2, 'x': 1}
>>> d.popitem()
('y', 2)
>>> d
{'x': 1}

 

 

12.setdefault

setdefault方法用于获得给定键相关联的值,还可以在字典中不含有给定键的情况下设定相应的键值

>>> d = {}
>>> d.setdefault('name','yumeng')
'yumeng'
>>> d
{'name': 'yumeng'}
>>> d['name']='lol'
>>> d
{'name': 'lol'}
>>> d.setdefault('name','gg')
'lol'
>>> d
{'name': 'lol'}

 

 

13.update

update方法用于利用一个字典项更新另外一个字典

>>> a = {'a':1,'b':2}
>>> a
{'a': 1, 'b': 2}
>>> b = {'b':'110'}
>>> a.update(b)
>>> a
{'a': 1, 'b': '110'}
>>> c = {'name':'yumeng'}
>>> a.update(c)
>>> a
{'a': 1, 'b': '110', 'name': 'yumeng'}

 

如果有相同的值会覆盖掉

 

14.values

values用于以列表的形式返回字典中的值

>>> x = {'name':'yumeng','age':20}
>>> x
{'age': 20, 'name': 'yumeng'}
>>> x.values()
[20, 'yumeng']

 

15.itervalues

itervalues用于以迭代器的形式返回字典中的值

>>> x = {'name':'yumeng','age':20}
>>> x
{'age': 20, 'name': 'yumeng'}
>>> x.itervalues()
<dictionary-valueiterator object at 0x01EF8DE0>

 

至此,完成。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics