繁体   English   中英

如何让用户在列表中添加或删除新项?

[英]How do I let the user add or remove new items to the list?

我正在看这个网站上有类似问题的其他python代码,但这些代码与我的有很大不同,看起来更令人困惑,因此阅读它们并没有多大帮助。 无论如何,我想看看我如何让用户在他们创建的列表中添加或删除,我该怎么做? 此代码中的所有内容都可以正常工作,但我只是想知道我需要添加什么,以便我可以让用户添加或删除项目。

temperatureList = list()

weather=int(input("Enter the amount of days that you are looking at for 
the weather:"))

print("Enter the high temperature for those next days: ")

for i in range(int(weather)):
    k=int(input(""))
    temperatureList.append(int(k))

sm=sum(temperatureList)

avg=sm/weather

print("SUM = ",sm)

print("AVERAGE = ",avg)

对于添加和删除,您可以有一个循环,不断要求用户添加和删除数字,并显示更新的统计信息,例如

while True:
    action = int(input("Input -1 if you want to add to the list again. Or -2 if you want to remove from the list"))

    if action == -1:
        print("Enter what you want to be added ")
        add = int(input(""))
        temperatureList.append(add)
        print(temperatureList)
        sm = sum(temperatureList)

        avg = sm / weather

        print("SUM = ", sm)

        print("AVERAGE = ", avg)
    elif action == -2:
        if len(temperatureList) > 1:
            del temperatureList[-1]
            print(temperatureList)
            sm = sum(temperatureList)
            avg = sm / weather
            print("SUM = ", sm)
            print("AVERAGE = ", avg)
        else:
            print("Everything removed from the list")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM