簡體   English   中英

比較和替換列表的元素

[英]Comparing and replacing elements of a list

我有一本字典: -

   dict= { 'b' : 'bob' , 'c' : 'code' , 'd' : 'do'}
import re
def convert(str)
 data=list(str.replace(' ',''))
 for dat in data
 print dat
 # this gives an output as
 # b
 # c
 # d
 # Here I want to compare each character(b,c,d) with the key in my dict{} dictionary
 # and if there is a match(dict has 'b':'bob') then I want to replace the character with the 
 # dictionary value.
 # In summary i want to convert string bcd to bobcodedo.


if __name__== "__main__":
 sam('bcd')

總之,我想將字符串bcd轉換為bobcodedo。

不要將你的dictionary命名為dictstring str等。

In [12]:

D={ 'b' : 'bob' , 'c' : 'code' , 'd' : 'do'}
S='bcd'
In [13]:

''.join(map(D.get,S))
Out[13]:
'bobcodedo'

將其擴展到第二個問題:

In [15]:

''.join(map(lambda x: D.get(x, ''),'bcdefg'))
Out[15]:
'bobcodedo'
In [16]:

''.join(map(lambda x: D.get(x, x),'bcdefg'))
Out[16]:
'bobcodedoefg'

要在評論中回答這個問題:

In [12]:

bad_str='|xyz'
in_str1='acdefggt'
in_str2='asxsttgm'
In [13]:

set(bad_str).intersection(in_str2)
Out[13]:
{'x'}
In [14]:

if len(set(bad_str).intersection(in_str1))==0:
    print 'do someting'
else:
    print 'Abort!'
do someting

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM