首页 > 解决方案 > PythonError:“浮动”对象不可迭代

问题描述

我正在尝试从 txt 文件中的向量列表中进行 3 个切片,其中包含 2 列,使用条件来分隔 RGB。

但是当我运行程序时,会出现以下错误:“'float' object is not iterable”。谁能帮我?

#File opening
arq = open('arquivo.txt','r')

lines = arq.readlines()
arq.close()

vetor_x = []
vetor_y = []
lista_geral = []

for line in lines:
    line = line.replace('\n','')
    line = line.strip()
    line = line.replace(',','.')
    line = line.split('\t')

    if(len(line) == 2):
        X = line[0]
        Y = line[1]
        vetor_x.append(float(X))
        vetor_y.append(float(Y))
        lista_geral.append([X,Y])

#Conditions
B = 0
G = 0
R = 0

for i in range(0,len(vetor_x)):

    if vetor_x[i] <= 500:
        vetor_xB[B] = list(vetor_x[i])
        vetor_yB[B] = list(vetor_y[i])
        B += 1

    elif vetor_x[i] <= 600:
        vetor_xG[G] = list(vetor_x[i])
        vetor_yG[G] = list(vetor_y[i])
        G += 1

    elif vetor_x[i] <= 700:
        vetor_xR[R] = list(vetor_x[i])
        vetor_yR[R] = list(vetor_y[i])
        R += 1

print('####### vetor_xB #######')
print(vetor_xB)
print('####### vetor_yB #######')
print(vetor_yB)
print('####### vetor_xG #######')
print(vetor_xG)
print('####### vetor_yG #######')
print(vetor_yG)
print('####### vetor_xR #######')
print(vetor_xR)
print('####### vetor_yR #######')
print(vetor_yR)

但是,当我尝试运行它时,会导致此错误:

Traceback (most recent call last):
  File "teste4.py", line 30, in <module>
    vetor_xB[B] = list(vetor_x[i])
TypeError: 'float' object is not iterable

请帮我!

标签: pythonpython-3.x

解决方案


在这段代码中

if vetor_x[i] <= 500:
    vetor_xB[B] = list(vetor_x[i])

if从您的-test 中可以清楚地看出您希望vetor_x[i]是一个数字;它是一个数字,否则你会在if-test 上得到一个运行时错误。

但是,您正在拨打list()这个号码。所以我怀疑这list(x)不会像你认为的那样做。它实际上所做的是获取所有元素x(可以是列表或元组或字符串或......)并将它们放入列表中。假设vetor_x[i] == 400.00000。然后你的代码正在做list(400.00000). 这是没有意义的。

我想你可能打算

if vetor_x[i] <= 500:
    vetor_xB.append(vetor_x[i])

...但这只是一个猜测。

您不能通过为不存在的元素分配值来使 Python 列表更长。因此,如果vetor_xB是一个空列表,那么分配vetor_xB[B] =将失败,因为无论 的值如何B,都没有元素B:如果B == 0thenvetor_xB[B]与 相同vetor_xB[0],并且尝试分配将失败,因为没有元素零。

因此,要使列表更长,请append()改用。但要附加到列表,列表必须首先存在。您的代码没有为vetor_xB. 在程序的顶部需要有类似vetor_xB == [].


推荐阅读