首页 > 解决方案 > 根据用户输入中的整数删除列表中的数据

问题描述

该问题希望我询问用户他们希望删除列表中的多少项目。(没有什么特别的,只是一些项目,可以是随机的..)输入在 1 到 4 之间。这是我的代码。

list2=[]
for i in range(5):
    counter = counter+1
    print("Item number : ", counter)
    ask = input("Type here to append to list: ",)
    addingList = list2.append(ask)
print("Here is your newly created list: ", list2)
i = True
t = 0

while i:
    dellist = int(input("Select the number of items to be deleted. 1 - 4"))
    if dellist not in range(1, 5):
        print("Invalid choice, Please select a number between 1-4.")
    else:
        break 

// Have also tried using the del cmd and its only removing 1 entry even tho 3/4 could be specified in input.

标签: python-3.x

解决方案


看看列表切片

我们使用该行list = list[:-n]使用负索引删除列表的最后 n 个元素。

工作代码片段:

list2 = []

for i in range(5):
    print("Item number : ", i+1)
    ask = input("Type here to append to list: ",)
    addingList = list2.append(ask)
print("Here is your newly created list: ", list2)
t = 0

while True:
    dellist = int(input("Select the number of items to be deleted. 1 - 4"))
    if dellist not in range(1, 5):
        print("Invalid choice, Please select a number between 1-4.")
    else:
        list2 = list2[:-dellist]
        break

推荐阅读