如果单词匹配
,我想将内部列表的第一个值(数字)传递给dict缓冲区:
['from',
'landi',
'stsci',
'edu',
'four'...]
list_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
谢谢。
答案 0 :(得分: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]
希望有所帮助!
答案 1 :(得分: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]
答案 2 :(得分: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]]
答案 3 :(得分:1)
那是因为list_1
中的每个元组只有2个项目:
>>> 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]]