我正在开发一个图像搜索引擎应用程序,我将代码放在单独的.py
文件中,它运行正常。但我想优化它。当我使用下面的函数时,它给了我一个ValueError。
我的代码是这样的(只有我采取的相关行):
def example():
i = 0
resultlist_key = []
result_list = list()
a_list = list()
b_list = list()
a_list.append(feature_matrix_ip)# feature_matrix_ip contains features of the query image
while i < 70:
b_list.append(feature_matrix_db[i])# feature_matrix_db contains features of img. in DB
dist = distance.euclidean(a_list,b_list[i])
result_list.append(dist)
resultlist_key = OrderedDict(sorted(enumerate(result_list),key=lambda x: x[0])).keys()
i = i + 1
res_lst_srt = {'values': result_list,'keys':resultlist_key}
res_lst_srt['values'], res_lst_srt['keys'] = zip(*sorted(zip(res_lst_srt['values'], res_lst_srt['keys'])))# sorting according to the least distance and the key will not change
key = res_lst_srt['keys']
当我分析时,我没有得到任何解决方案。我的错误陈述是:
%run "D:/6th sem/Major project/Code/frame.py"
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.0.3.1262.win-x86\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "D:\6th sem\Major project\Code\frame.py", line 323, in matching_image
res_lst_srt['values'], res_lst_srt['keys'] = zip(*sorted(zip(res_lst_srt['values'], res_lst_srt['keys'])))
ValueError: need more than 0 values to unpack
我不知道这个错误是否来自命名问题。当代码在函数外部时,它将正常工作,但我希望代码在函数内部,以便优化程序。
有关解决此错误的任何建议吗?
答案 0 :(得分:0)
所以,我的猜测是这部分:
zip(*sorted(zip(res_lst_srt['values'], res_lst_srt['keys'])))
将空列表返回给zip
的任何一个:
>>> foo, bar = []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack
现在,如果您想要填充res_lst_srt
(因为我似乎从您的问题中了解到),为什么不让它变得更简单?
>>> values=[1,2,3]
>>> keys=['a', 'b', 'c']
>>> my_dict = dict(zip(keys, values))
>>> my_dict
{'a': 1, 'c': 3, 'b': 2}
(values
此处为res_lst_srt['values']
,keys
为res_lst_srt['keys']
,my_dict
为res_lst_srt
。否?不应该工作?
答案 1 :(得分:0)
通过查看这个简单的案例可以找到您的问题。
>>> a, b = tuple() # or you could write a, b = []
Traceback (most recent call last):
File "<pyshell#319>", line 1, in <module>
a, b = tuple()
ValueError: need more than 0 values to unpack
>>>
equals运算符一侧的值长度必须与另一侧匹配。
所以很明显,..
返回的值zip(*sorted(zip(res_lst_srt['values'], res_lst_srt['keys'])))
..最终返回一个空列表/元组。这让你感到悲伤。