我正在编写一个接受参数的函数。从该参数,我想将它与字典的键集进行比较,并为任何匹配返回键的值。到目前为止,我只能返回键的参数匹配。
def func(str):
a = []
b = {'a':'b','c':'d','e':'f'}
for i in str:
if i in b.keys():
a.append(i)
return a
输出样本:
FUNC( 'abcdefghiabcdefghi')
[ '一个', 'C', 'E', 'A', 'C', 'E']
通缉输出:
[ 'B', 'd', 'F', 'B', 'd', 'F']
答案 0 :(得分:2)
最好不要将str
用作变量名。我认为你的函数可以更简单地写成这样的
def func(mystr):
b = {'a':'b','c':'d','e':'f'}
return [b[k] for k in mystr if k in b]
如果您不想使用列表推导,那么您可以像这样修复它
def func(mystr):
a = []
b = {'a':'b','c':'d','e':'f'}
for i in mystr:
if i in b: # i in b works the same as i in b.keys()
a.append(b[i]) # look up the key(i) in the dictionary(b) here
return a