如果嵌套列表部分匹配另一个嵌套列表的子列表,则返回嵌套列表的子列表

时间:2019-07-19 13:37:43

标签: python

我有一个英语单词频率列表,在嵌套列表中包括该单词,其词性(POS)和其频率

freq_list = 
[['such', 'JJ', '17930'],
['year', 'NN', '17920'],
['as', 'RB', '17107']]

我还有一个嵌套的令牌列表,其中包含单词和POS。

tokens = 
[['legend', 'NN'], 
['of', 'IN'], 
['zelda', 'NN']]

我想比较列表,如果令牌中的单词和POS位于freq_list中,我想将freq_list中的最后一个值附加到令牌中。


    def get_frequency(self, tokens, freq_list):
            self.__frequencies = []
            for token in self.tokens:
                if token[0] in [item[0] for item in self.freq_list] and 
    token[1] in [item[1] for item in self.freq_list]]:
                    freq = token, self.freq_list(i)

我在最后一行中苦苦挣扎,后者定义了频率。我希望它是来自令牌的单词和POS(或来自freq_list,它们应该相同)以及来自freq_list的相应频率。任何建议都会很棒。

此外,我需要使用if语句,因为将要满足另外两个条件(例如,如果self.freq_list中的token [0]以及是否没有token [0]和token [1]都没有。

2 个答案:

答案 0 :(得分:0)

您必须遍历两个列表,检查匹配项,然后将第三项附加到另一个列表:

正常循环:

for x in tokens:
    for y in freq_list:
        if x == y[:2]:
            x.append(y[2])

答案 1 :(得分:0)

使用字典而不是嵌套列表来建模可能会更好:

freqs = {}
for word, pos, f in freq_list:
    if word not in freqs: freqs[word] = {}
    freqs[word][pos] = f

for i, (word, pos) in enumerate(tokens):
    if word not in freqs:
        tokens[i].append(0)  # fix for scenario #2
        continue
    if pos not in freqs[word]:  # fix for scenario #1
        pos = "UNK"
        if pos not in freqs[word]: continue
        tokens[i].append(freqs[word][pos])
        continue
    tokens[i].append(freqs[word][pos])
相关问题