[英]Comparing and replacing elements of a list
I have a dictionary :- 我有一本字典: -
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')
In summary i want to convert string bcd to bobcodedo. 总之,我想将字符串bcd转换为bobcodedo。
Don't name your dictionary
dict
, string
str
, etc. 不要将你的
dictionary
命名为dict
, string
str
等。
In [12]:
D={ 'b' : 'bob' , 'c' : 'code' , 'd' : 'do'}
S='bcd'
In [13]:
''.join(map(D.get,S))
Out[13]:
'bobcodedo'
To expand it to your second question: 将其扩展到第二个问题:
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'
To answer the question in your comment: 要在评论中回答这个问题:
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.