偶然看到一個這個文章,替換元素大家應該都有方法去做,但是作者用的方法之前沒有接觸過,感覺比較好玩,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']
'''