【问题标题】:Replace each element from a list with another from a dictionary list将列表中的每个元素替换为字典列表中的另一个元素
【发布时间】:2021-07-16 05:38:31
【问题描述】:

简而言之,我需要为列表中的每个元素从字典列表中获取相应的值并替换它 例如...对于以下输入列表

list1 = ['gui', 'guigui', 'guiguigguuii']
list2 = ['gui', 'gui', 'gui', 'gui', 'gui', 'gui']

我应该在那些字典列表中查找

dictlist1 = [{'gui': 'ya'}, {'guigui': 'lyub'}, {'guiguigguuii': 'htr'}]
dictlist2 = [{'gui': 'asdf'}]

它应该输出

output1 = ['ya', 'lyub', 'htr']
output2 = ['asdf', 'asdf', 'asdf', 'asdf', 'asdf', 'asdf']

我已经写了一个代码...但是它不适用于第二个数据样本

print(' '.join([item for sublist in [[value for key, value in d.items()] for d in lista] for item in sublist]))

【问题讨论】:

    标签: python list dictionary for-loop list-comprehension


    【解决方案1】:

    在这里,抱歉,如果它有点长,但是,我认为使用这个模板你可以解决一些问题。

    list1 = ['gui', 'guigui', 'guiguigguuii']
    replace = [{'gui': 'ya'}, {'guigui': 'lyub'}, {'guiguigguuii': 'htr'}]
    newList = []
    #iterate through list1
    for words in list1:
        count = 0
        #iterate through replaces dicts
        for dicts in replace:
            #Check if any word in list1 can be replaced
            if words == list(dicts.keys())[0]:newList.append(dicts[list(dicts.keys())[0]])
            count += 1
    print(newList)
    

    输出

    ['ya', 'lyub', 'htr']
    

    【讨论】:

    • 第 10 行的 dcs.keys() 是什么?
    • 我的糟糕忘了更改它。为澄清起见,它返回 replace. 中的所有键
    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2018-08-19
    • 2022-10-20
    • 2021-05-19
    • 2021-12-12
    • 2023-03-19
    • 2016-03-28
    相关资源
    最近更新 更多