我在python中有以下代码:
features = {}
for string in vector:
string = 'name1:value1 name2:value2 name3:value3'
name,value = string.split(":");
features[self._getFeatureId(name)] = float(value);
return features
但是当我运行代码时,它会出现以下错误:
name,value = string.split(":");
ValueError: too many values to unpack
这是一个for循环,它假定将它们分成3对不同的名称和值。代码有什么问题?
答案 0 :(得分:3)
string = "name1:value1 name2:value2 name3:value3"
split_on_colon = string.split(":"); # output = ['name1', 'value1 name2', 'value2 name3', 'value3']
split_on_space = string.split(); # No argument means split on white space; output = ['name1:value1', 'name2:value2', 'name3:value3']
# The split you desire is on space and THEN split each item on colon
desired_split = [s.split(':') for s in string.split()] # output = [['name1', 'value1'], ['name2', 'value2'], ['name3', 'value3']]
此外,错误ValueError: too many values to unpack
也无法清除。从字面上说,您正在尝试解压缩比迭代器中小的值。
答案 1 :(得分:0)
我还设法使它与以下代码一起使用,方法是先用“”分割,然后对每个名称值对,用“:”分割。
features = {}
for string in vector:
string = name1:value1 name2:value2 name3:value3
valueTemp = string.split(" ");
for string2 in valueTemp:
name,value = string2.split(":");
features[self._getFeatureId(name)] = float(value);
return features