2

如果单词匹配,我想将内部列表的第一个值(数字)传递给 dict

缓冲 :

 ['from', 
'landi', 
'stsci', 
'edu', 
'four'...]

列表_1:

[('focus', [-1, -2]), 
('four', [-3.3, -1.04]),
...)]

for key in docs_A_rec:
    for word, number_1,number_2  in list_1:
       if word in buffer:
           docs_A_rec[key]['idf'][word] = list_1[word][number_1]

我收到此错误:

ValueError: need more than 2 values to unpack

谢谢你。

4

4 回答 4

3

您的第二个循环中有一个错误,将其修复如下:

for key in docs_A_rec:
    for word, (number_1,number_2)  in list_1:
       if word in buffer:
           docs_A_rec[key]['idf'][word] = templist[word][number_1]

希望有所帮助!

于 2013-08-06T17:29:42.977 回答
2

应该是这样的:

[('focus', [-1, -2]), 
('four', [-3.3, -1.04]),
...)]

for key in docs_A_rec:
    for word, (number_1,number_2)  in list_1:
       if word in buffer:
           docs_A_rec[key]['idf'][word] = list_1[word][number_1]
于 2013-08-06T17:28:45.090 回答
1
>>> buffer = ['from', 'landi', 'stsci', 'edu', 'four']
>>> list_1 = [('focus', [-1, -2]), ('four', [-3.3, -1.04])]
>>>
>>> for key1 in buffer:
...   for key2 in list_1:
...     if (key1 != key2[0]):
...       continue;
...     print key1
...     print key2[1][0]
...
four
-3.3
>>>

所以,以下应该足够了,

for key1 in buffer:
  for key2 in list_1:
    if (key1 == key2[0]):
      list_1[key1][key2[1][0]]
于 2013-08-06T17:33:02.743 回答
1

那是因为每个元组中只有 2 项 in list_1

>>> list_1 = [('focus', [-1, -2]), ('four', [-3.3, -1.04])]
>>> list_1[0]
('focus', [-1, -2])
>>> len(list_1[0])
2
>>>

但您要求 3(“word”、“number_1”和“number_2”):

for word, number_1,number_2  in list_1:

要解决此问题,请稍微更改您的 for 循环,如下所示:

for key in docs_A_rec:
    # Add parenthesis around "number_1 , number_2"
    for word, (number_1, number_2) in list_1:
       if word in buffer:
           docs_A_rec[key]['idf'][word] = list_1[word][number_1]

或使用索引:

for key in docs_A_rec:
    # Put the second item of each tuple in 'numbers'
    for word, numbers in list_1:
       if word in buffer:
           # Index 'numbers' at 0 to get the first number (the same as number_1)
           docs_A_rec[key]['idf'][word] = list_1[word][numbers[0]]
于 2013-08-06T17:36:44.187 回答