Python 替换列表元素

来源:互联网 发布:mac注销appstore 编辑:程序博客网 时间:2024/06/06 17:09

Python里字符串有replace方法,但是List没有replace的方法:

>>> lst = ['1','2','3']>>> lst.replace('1', '4')Traceback (most recent call last):  File "", line 1, in AttributeError: 'list' object has no attribute 'replace'

可以用列表解析的方法实现元素替换,下例里把 ‘1’ 替换成 ‘4’ :

>>> lst = ['1', '2', '3']>>> rep = ['4' if x == '1' else x for x in lst]>>> rep['4', '2', '3']>>>

批量替换,即把一个列表里的元素全部替换成同一个元素,下例里把 ‘3’ 和 ‘4’ 都替换成’d’:

>>> lst = ['1', '2', '3', '4', '5']>>> pattern = ['3', '4']>>> rep = ['d' if x in pattern else x for x in lst]>>> rep['1', '2', 'd', 'd', '5']>>>

映射替换,根据一个字典的映射关系替换,下例里把 ‘3’ 和 ‘4’ 都替换成英文:

>>> lst = ['1', '2', '3', '4', '5']>>> pattern = {'3':'three', '4':'four'}>>> rep = [pattern[x] if x in pattern else x for x in lst]>>> rep['1', '2', 'three', 'four', '5']>>>

原文链接:http://www.lfhacks.com/tech/python-list-element-replace

0 0
原创粉丝点击