我正在用 Python编写程序,并试图扩展一个列表: spectrum_mass[second] = [1.0, 2.0, 3.0]spectrum_intensity[second] = [4.0, 5.0, 6.0]spectrum_mass[first] = [1.0, 34.0, 35.0]spectrum_intensity[second] = [7.0, 8.0, 9.0]for i in s
spectrum_mass[second] = [1.0, 2.0, 3.0] spectrum_intensity[second] = [4.0, 5.0, 6.0] spectrum_mass[first] = [1.0, 34.0, 35.0] spectrum_intensity[second] = [7.0, 8.0, 9.0] for i in spectrum_mass[second]: if i not in spectrum_mass[first]: spectrum_intensity[first].extend(spectrum_intensity[second][spectrum_mass[second].index(i)]) spectrum_mass[first].extend(i)
但是,当我尝试这样做时,我得到TypeError:’float’对象不可迭代
在第3行.
为了清楚起见,spectrum_mass [second]是一个列表(在字典中,第二个和第一个是键),如spectrum_intensity [first],spectrum_intensity [second]和spectrum_mass [second].所有列表都包含浮点数.
我猜这个问题与线路有关 –spectrum_intensity[first].extend(spectrum_intensity[second][spectrum_mass[second].index(i)])
extend()函数需要一个可迭代的,但是你试图给它一个浮点数.在一个非常小的例子中相同的行为 –
>>> l = [1,2] >>> l.extend(1.2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'float' object is not iterable
你想使用.append()代替 –
spectrum_intensity[first].append(spectrum_intensity[second][spectrum_mass[second].index(i)])
同样的问题也在下一行中,使用append()而不是extend() –
spectrum_mass[first].extend(i)