Skip to main content
 首页 » 编程设计

python之TypeError : list indices must be integers or slices, 不 float

2024年12月31日7del

def convBin(): 
    cont = [] 
    rest = [] 
    dev = [] 
    decimal = [] 
 
    print("Ingrese el valor a convertir: ") 
    valor = ast.literal_eval(input()) 
 
    if isinstance(valor, int): 
        while valor > 0: 
                z = valor // 2 
            resto = valor%2 
            valor = valor // 2 
            cont.append(z) 
            rest.append(resto) 
 
        cont.reverse() 
        rest.reverse() 
 
        dev.append(cont[0]) 
 
        x = 0 
        while x <= (len(rest) - 1): 
            dev.append(rest[x]) 
            x += 1 
 
        print(" ") 
        print("Lista de devoluciones: ") 
        print(dev) 
        print("") 
 
    elif isinstance(valor, float): 
        a = valor // 1 
        b = valor % 1 
 
        while a > 0: 
            z = a // 2 
            resto = a%2 
            a = a // 2 
            cont.append(z) 
            rest.append(resto) 
 
        cont.reverse() 
        rest.pop() 
 
        dev.append(cont[1]) 
 
        for i in rest: 
            dev.append(rest[i]) 
 
        print("Inserte el número de error minimo") 
        num = input() 
 
        while num > 0: 
            dec = b * 1 
            dec2 = dec//1 
            dec %= 1         
            decimal.append(dec2) 
 
 
        print("Parte entera: ") 
        print(dev) 
        print("Parte decimal:") 
        print(num) 
 
    else: 
        print("Ha aparecido un error") 

它向我显示了一个错误,我无法将 float append 到列表中。

问你一个数字后,它会控制它是哪种类型的数字。当它是一个int时,它没有任何问题。但是当它是一个 float 时,它说它不能将一个 float 添加到一个列表中,它保存了之前进行的操作的数量。

谁能给我解释一下为什么我不能将 float append 到列表中,或者我该如何解决这个问题?

Traceback (most recent call last): File "Converter.py", line 169, in convBin(); File "Converter.py", line 53, in convBin dev.append(rest[i]) TypeError: list indices must be integers or slices, not float

谢谢。

请您参考如下方法:

for i in rest 将为您提供列表中的实际项目,而不是索引。从您的代码来看,您似乎想要 append 该值。但实际上,您再次将该值视为索引,并尝试从数组中获取它。

for i in rest: 
            dev.append(rest[i]) 

修复:

只需将上面的内容更改为:

dev.extend(rest) 

但是这段代码从 rest 中获取一个值,然后再次使用该值作为索引,如果该值 i 结果是一个 float,它会抛出一个异常(exception)。

你没有提到哪一行给你这个错误。但我想一定是这一个。它可能会产生许多其他意外错误,例如 array out of bound 等

这是我得到的错误,如果我为 valor = 18.5 运行你的代码

https://ideone.com/HGagLb

Traceback (most recent call last): File "./prog.py", line 71, in File "./prog.py", line 51, in convBin TypeError: list indices must be integers or slices, not float

上面的例子和下面的例子(从你的代码,你处理 int 的地方)的区别:

x = 0 
while x <= (len(rest) - 1): 
    dev.append(rest[x]) 
    x += 1 

就是,在第一种情况下,i 实际上是列表 rest 中的项(int 或 float),而在后一种情况下,它是一个有效的索引。