简体   繁体   English

如何将键值对匹配到多维列表?

[英]how to match key value pairs to a multi-dimensional list?

given a multidimensional list:给定一个多维列表:

a = [[7, 5, 1, 9, 4],
 [20, 11, 15, 17, 16],
 [23, 21, 24, 25, 30],
 [36, 34, 32, 40, 31],
 [44, 49, 42, 43, 50]]

and a dictionary like that:和这样的字典:

dict_words = {"yes":42,"no":16,"good morning":9,"morning sir":34}

how can I iterate over the list and match the dictionary key-value pairs to reach my desired output as such:我如何遍历列表并匹配字典键值对以达到我想要的 output 如下:

a_processed = [[7, 5, 1, "good morning", 4],
 [20, 11, 15, 17, "no"],
 [23, 21, 24, 25, 30],
 [36, "morning sir", 32, 40, 31],
 [44, 49, "yes", 43, 50]]

all i found is how to exchange 1d-lists, https://www.geeksforgeeks.org/python-assigning-key-values-to-list-elements-from-value-list-dictionary/ , but when I try that I receive a TypeError: argument of type 'int' is not iterable我发现的只是如何交换一维列表https://www.geeksforgeeks.org/python-assigning-key-values-to-list-elements-from-value-list-dictionary/ ,但是当我尝试时,我收到TypeError: argument of type 'int' is not iterable

My code so far:到目前为止我的代码:

a = [[7, 5, 1, 9, 4],
 [20, 11, 15, 17, 16],
 [23, 21, 24, 25, 30],
 [36, 34, 32, 40, 31],
 [44, 49, 42, 43, 50]]

dict_words = {"yes":42,"no":16,"good morning":9,"morning sir":34}

a_processed = [key for ele in a
   for key, val in dict_words.items() if ele in val]

Try this,尝试这个,

a = [
    [7, 5, 1, 9, 4],
    [20, 11, 15, 17, 16],
    [23, 21, 24, 25, 30],
    [36, 34, 32, 40, 31],
    [44, 49, 42, 43, 50],
]
dict_words = {"yes": 42, "no": 16, "good morning": 9, "morning sir": 34}
remap_dict = {value: key for key, value in dict_words.items()}
a_replaced = [[remap_dict.get(item, item) for item in row] for row in a]
print(a_replaced)

This is for loop version, you can use this compare with upper version这是for循环版本,你可以用这个比较上版本

remap_dict = {value: key for key, value in dict_words.items()}
print(remap_dict)
a_replaced = []
for row in a:
    new_row = []
    a_replaced.append(new_row)
    for item in row:
        if item in remap_dict:
            new_row.append(remap_dict[item])
        else:
            new_row.append(item)
print(a_replaced)

This is for loop version with change value in a inplace, be careful, this will change the matrix "a"这是在原地改变值的 for 循环版本,小心,这将改变矩阵“a”

remap_dict = {value: key for key, value in dict_words.items()}
print(remap_dict)
for row in a:
    for item_index in range(len(row)):
        if row[item_index] in remap_dict:
           row[item_index] = remap_dict[row[item_index]]

print(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM