【问题标题】:I'm trying to make a piece of code where a user inputs 5 numbers and the code will remove the 5th number. What is wrong with my code?我正在尝试制作一段代码,其中用户输入 5 个数字,代码将删除第 5 个数字。我的代码有什么问题?
【发布时间】:2017-04-03 10:32:18
【问题描述】:

这是我到目前为止所做的:

def remove_five ():
    list = []
    for x in range(0, 4):
        number = input("Enter a number")
        list.append(number)
    end
    fifth = list[4]
    list.remove(fifth)

remove_five()

我在运行程序时收到“TypeError”。这就是它所说的: Traceback(最近一次调用最后一次):

文件“G:fivealive.py”,第 6 行,在 list.append(数字) TypeError:描述符“追加”需要一个“列表”对象,但收到了一个“字符串”

【问题讨论】:

  • input() 返回一个String,append需要一个列表,是不是不够清楚?
  • 我没有收到该错误,但您的代码存在一些问题:1) 确保您的缩进是正确的。 2)如果您希望输入 5 个数字,请创建循环“for x in range(0,5)” 3)您不必将 end 放在 for 循环的末尾 4)列表只存在于这个函数,函数结束后没有任何作用
  • 这里的end 是什么?您不应该使用 list 作为变量,因为它是 Python 中的内置数据类型。你在这里提到的代码并不是给你这个错误的实际代码。可能是你有number = input(),然后你正在做list.append(),这导致了这个错误,因为input()返回的值将是str类型

标签: python list append typeerror


【解决方案1】:
  1. 保持缩进正确。
  2. range(0, 4) 将生成 0..3。你想要range(5)
  3. 如果需要数字,请将输入转换为整数。
  4. 使用del 操作删除元素。
  5. 返回创建的列表。
  6. 不要使用list作为变量名,因为它是内置类型

修复它的结果应该是这样的:

def remove_five ():
    my_list = []
    for x in range(5):
        number = int(input("Enter a number"))
        my_list.append(number)
    del my_list[4]
    return my_list 

my_list = remove_five()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    相关资源
    最近更新 更多