如何用字典中的值替换列表项中的字符作为键

时间:2018-10-30 16:30:23

标签: python python-3.x list dictionary data-structures

我正在尝试做这样的事情:

我的输入

predefined_list=['gross pay']
predefined_dict={'a':'o','o':'a','g':'c','c':'g'}

所需

output: ['gross pay', 'gross poy', 'grass pay', 'crass pay', cross pay, crass poy] 

和其他几种组合。

我尝试过:

predefined_list=['gross pay']
predefined_dict={'a':'o','o':'a','g':'c','c':'g'}

i=0;
for key,value in predefined_dict.items():
    final=predefined_list[i].replace(key,value)
    i+=1
    if final not in predefined_list:
        predefined_list.append(final)
print(predefined_list)

2 个答案:

答案 0 :(得分:1)

只需通过遍历字典的键和值来替换字符串

modified_list = [predefined_list[0].replace(k,v) for k,v in predefined_dict.items()]

输出

['gross poy', 'grass pay', 'cross pay', 'gross pay']

类似地

predefined_list = ['pay gross', 'gross pay']
modified_dict = {list_k: [list_k.replace(k,v) for k,v in predefined_dict.items()]
                 for list_k in predefined_list}

输出

{'gross pay': ['gross poy', 'grass pay', 'cross pay', 'gross pay'],
 'pay gross': ['poy gross', 'pay grass', 'pay cross', 'pay gross']}

答案 1 :(得分:0)

尝试这种方式

for key, value in predefined_dict.items():
        for  word in predefined_list:
            for n in range(word.count(key)):
                final = word.replace(key,value,n+1)
                if final not in predefined_list:
                    predefined_list.append(final)

输出:

>>> predefined_list

['gross pay', 'gross poy', 'grass pay', 'grass poy', 'cross pay', 'cross poy', 'crass pay', 'crass poy']