我正在尝试在python中添加两个稀疏向量。到目前为止,我已经能够添加和合并向量。但是我迷失了到底,这给了我'int'对象不是可迭代的错误。另外,由于这些稀疏向量被转换成python字典,我不知道字典中如何包含零值。
def SparseVec(numbers):
dic={}
for key,val in enumerate(numbers):
if val:
dic[key]=val
return dic
numbers=[-1,0,9.2,0]
a=SparseVec(numbers)
print(a)
numbers2=[0,1,0,0,0]
b=SparseVec(numbers2)
print(b)
#Adds and merges values with keys in two dictionaries
def merged_dictionaries(a,b):
merged_dict={}
for key in a:
if key in b:
new_value=a[key]+b[key]
else:
new_value=a[key]
merged_dict[key]=new_value
for key in b:
if key not in merged_dict:
merged_dict[key]=b[key]
return merged_dict
c=merged_dictionaries(a,b)
for key, val in c.items (): # SparseVec iterator
print ('c[%d]=%g ' % (val, key))
print(c)
控制台错误:
C:\Python27\python.exe C:/Users/GISN24/Ex_06/E06/SparseVec.py
{0: -1, 2: 9.2}
{1: 1}
Traceback (most recent call last):
File "C:/Users/Kaleab/Desktop/GISN24/Ex_06/E06/SparseVec.py", line 30, in <module>
for key, val in c: # SparseVec iterator
TypeError: 'int' object is not iterable
Process finished with exit code 1