python direct replacement elements in the list four methods

The elements in the list changes directly replace.

Examples: aaa surface elements in the list of 'black' replaced 'yellow'.

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

The first method (not recommended):

aaa=['黑色','红色','白色','黑色']
aaa=str(aaa)
bbb=aaa.replace("黑色","黄色")
bbb

结果:
"['黄色', '红色', '白色', '黄色']"

The second method:

aaa=['黑色','红色','白色','黑色']
bbb=['黄色' if i =='黑色' else i for i in aaa]
bbb

结果:
['黄色', '红色', '白色', '黄色']

A third alternative method :( volume element)

aaa=['黑色','红色','白色','黑色']
ccc=['黑色','红色']
bbb=['黄色' if i in ccc  else i for i in aaa]
bbb

结果:
['黄色', '黄色', '白色', '黄色']

Alternatively the plurality of elements :( fourth method)

aaa=['黑色','红色','白色','黑色']
ccc={'黑色':'黄色','红色':'白色'}
bbb=[ccc[i] if i in ccc else i for i in aaa]
bbb

结果:
['黄色', '白色', '白色', '黄色']

 

Published 35 original articles · won praise 26 · views 80000 +

Guess you like

Origin blog.csdn.net/weixin_42342968/article/details/84105061