如何将与第一个列表中的单词匹配的列表列表中的单词替换为与第二个列表中的第一个单词具有相同位置的单词?

问题描述 投票:2回答:2

我有一个字符串类型的列表列表,其中包含需要替换的单词。

可以通过检查列表1中是否存在匹配来进行该替换,如果存在则在列表2中搜索匹配的位置。从列表2中的该位置挑选该单词并替换在列表的原始列表中。

注意:匹配项可能不会出现在列表列表的所有子列表中。


list_of_list = [['apple', 'ball', 'cat'], ['apple', 'table'], ['cat', 'mouse', 'bootle'], ['mobile', 'black'], ['earphone']]

list_1 = ["apple", "bootle", "earphone"]

list_2 = ["fruit", "object", "electronic"]

This is what I have tried so far, but it doesn't seem to work the way I want it to. 

for word in list_of_list:
    for idx, item in enumerate(word):
        for w in list_1:
            if (w in item):
                index_list_1= list_1.index(w)
                word_from_list_2 = list_2[index_list_1]
                word[idx] = word_from_list_2
print(list_of_list)

我想要的东西:

输入:

list_of_list = [['apple', 'ball', 'cat'], ['apple', 'table'], ['cat', 'mouse', 'bootle'], ['mobile', 'black'], ['earphone']]

输出:

list_of_list = [['fruit', 'ball', 'cat'], ['fruit', 'table'], ['cat', 'mouse', 'object'], ['mobile', 'black'], ['electronic']]
python nlp
2个回答
2
投票

这是使用nested list comprehension的一种方法,并使用list_1list_2中的字典构建映射嵌套列表中的值:

d = dict(zip(list_1, list_2))
# {'apple': 'fruit', 'bootle': 'object', 'earphone': 'electronic'}
[[d.get(i, i) for i in l] for l in list_of_list]

产量

[['fruit', 'ball', 'cat'], ['fruit', 'table'], ['cat', 'mouse', 'object'], 
 ['mobile', 'black'], ['electronic']]

这相当于以下内容:

res = [[] for _ in range(len(list_of_list))]
for ix, l in enumerate(list_of_list):
    for s in l:
        res[ix].append(d.get(s, s))
# [['fruit', 'ball', 'cat'], ['fruit', 'table'], ['cat', 'mouse', 'object'], 
#  ['mobile', 'black'], ['electronic']]

有些内容可能会对您有所帮助:


0
投票

如果要替换原始列表中的单词而不创建新列表,可以这样做:

list_of_list = [['apple', 'ball', 'cat'], ['apple', 'table'], ['cat', 'mouse', 'bootle'], ['mobile', 'black'], ['earphone']]

list_1 = ["apple", "bootle", "earphone"]
list_2 = ["fruit", "object", "electronic"]

replacements = dict(zip(list_1, list_2))

for sublist in list_of_list:
    for index, word in enumerate(sublist):
        if word in replacements:
            sublist[index] = replacements[word]

print(list_of_list)
# [['fruit', 'ball', 'cat'], ['fruit', 'table'], ['cat', 'mouse', 'object'], ['mobile', 'black'], ['electronic']]
© www.soinside.com 2019 - 2024. All rights reserved.