[Python]替换列表中的元素 以及列表生成式的用法

偶然看到一个这个文章,替换元素大家应该都有方法去做,但是作者用的方法之前没有接触过,感觉比较好玩,mark记录学习下。

<替换方法>文章出自:https://blog.csdn.net/weixin_42342968/article/details/84105061

列表元素替换

把列表中的元素直接更改、替换。

例子:表面列表aaa中的元素‘黑色’替换成‘黄色’。

aaa=['black','red','white','black']

第一种方法:

aaa=['black','red','white','black']
aaa=str(aaa)
bbb=aaa.replace("black","yellow")
print bbb
'''
['yellow', 'red', 'white', 'yellow'] 
'''

第二种方法:

aaa=['black','red','white','black']
bbb=['yellow' if i =='black' else i for i in aaa]
print bbb
'''
['yellow', 'red', 'white', 'yellow']
'''

第三种方法:(替换批量的元素)

aaa=['black','red','white','black']
ccc=['black','red']
bbb=['yellow' if i in ccc  else i for i in aaa]
print bbb
'''
['yellow', 'yellow', 'white', 'yellow']
'''

第四种方法:(替换多个元素)

aaa=['black','red','white','black']
ccc={'black':'yellow','red':'white'}
bbb=[ccc[i] if i in ccc else i for i in aaa]
print bbb
'''
['yellow', 'white', 'white', 'yellow']
'''

第一种方法不言而喻,可以做到但是还要再处理一次因为属性是str,后面的条件写法第一次见到,查询了下才知道这种写法叫做列表生成式,很新奇哎,感觉还挺实用的????..

列表生成式:

首先,列表生成式有两种形式:

1. [x for x in data if condition]

此处if主要起条件判断作用,data数据中只有满足if条件的才会被留下,最终生成一个数据列表。

list1 = [i for i in range(1,10) if i%2==1]
print list1
'''
[1, 3, 5, 7, 9]
'''

2. [exp1 if condition else exp2 for x in data]

此处if…else主要起赋值作用。当data中的数据满足if条件时,将其做exp1处理,否则按照exp2处理,最终生成一个数据列表。

list2=['R','G','B','W']
list3=['R','G']

list4 = [i if i in list3 else i for i in list2]
print list4
'''
['R', 'G', 'B', 'W']
'''

实例拓展:

可以用列表生成式来对列表元素过滤。

一 .大小写转换

def toUpper(L):
    return [x.upper() for x in L if isinstance(x,str)]

def toLower(L):
    return [x.lower() for x in L if isinstance(x,str)]

print toUpper(['heelow','worrrd',111])
print toLower(['heelow','worrrd',111])

'''
['HEELOW', 'WORRRD']
['heelow', 'worrrd']
'''

二.list 去除指定重复元素

import copy
def filterDup(L,target):
    temp=copy.copy(L)
    temp_L = [L.remove(target) if (L.count(target) >=2 and x == target) else x for x in temp]
    for x in temp_L:
        if not x:
            temp_L.remove(x)
    return temp_L

list5=['R','G','B','W','B','G','R','R','W','C']
list6 = filterDup(list5,'R')
print list6
'''
['G', 'B', 'W', 'B', 'G', 'R', 'W', 'C']
'''