Skip to main content
 首页 » 编程设计

python之从 python3.3 中的两个嵌套列表添加 unigram 值

2024年11月01日12dflying

我有两个不同的嵌套列表 x 和 y,它们包含来自庞大语料库的单词的 unigrams 值。演示列表如下:

x = [['ali', '225'], ['raheem', '4514'], ['mohammed', '19652']] 
y = [['ali', '45514'], ['mohammed', '441'], ['salwa', '41']] 

如您所见,在 x 和 y 嵌套列表中都可以找到一个词,但它们的值不同。使用 Python3.3,我尝试比较这两个列表,并将 y 中某个单词的 unigram 值添加到 x 中的相应单词。但是,我收到一条消息错误:

Traceback (most recent call last): 
File "<pyshell#120>", line 1, in <module> 
add_unigrams(x, y) 
File "C:/Python33/add_unigrams.py", line 9, in add_unigrams 
x[i][0] = x[i][0], x[i][1] = int(x[i][1]) + int(y[i][1]) 
TypeError: 'int' object is not iterable 

如果能帮助我使代码正常工作,我将不胜感激。这是我的代码:

def add_unigrams(x, y): 
'''(lst, lst) -> lst 
Compare the items of y to items of x, add the unigrams of similar words 
in y to the value of the corresponding words in x. If an item in y is not found  
in x, then x.append(item). 
 
>>> add_unigrams(x, y) 
[['ali', '45739'], ['raheem', '4514'], ['mohammed', '20093'], ['salwa', '41']] 
''' 
 
i = 0 
j = 0 
 
for i in range(len(x)): 
    for j in range(len(y)): 
        if x[i][0] == y[j][0] and len(x[i]) == len(y[j]): 
            x[i][0] = x[i][0] 
            x[i][1] = int(x[i][1]) + int(y[i][1]) 
            i = i + 1 
            j = j + 1 
    for item in x: 
        for item in y: 
            if (not item in x): 
                x.append(item) 
 
 
return x 

我想实现两个字典来完成相同的任务,但我不知道该怎么做。示例:

d1 = { 'ali': 225, 'raheem' : 4514, 'mohammed' : 19652} 
d2 = { 'ali': 45514, 'mohammed' : 441, 'salwa' : 41} 

非常感谢任何帮助! 穆罕默德

请您参考如下方法:

IIUC,我不使用列表,而是使用 collections.Counter目的。例如:

>>> x = [['ali', '225'], ['raheem', '4514'], ['mohammed', '19652']] 
>>> y = [['ali', '45514'], ['mohammed', '441'], ['salwa', '41']] 
>>> x = [[k, int(v)] for k,v in x] 
>>> y = [[k, int(v)] for k,v in y] 
>>> Counter(dict(x)) 
Counter({'mohammed': 19652, 'raheem': 4514, 'ali': 225}) 
>>> Counter(dict(x)) + Counter(dict(y)) 
Counter({'ali': 45739, 'mohammed': 20093, 'raheem': 4514, 'salwa': 41})