python-3.x - 根据用户输入中的整数删除列表中的数据
问题描述
该问题希望我询问用户他们希望删除列表中的多少项目。(没有什么特别的,只是一些项目,可以是随机的..)输入在 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.
解决方案
看看列表切片
我们使用该行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
推荐阅读
- ios - Ionic 3 键盘在 ion 页脚仅 IOS 上无法正常工作
- python - 将行信息与列标题结合以创建一个变量
- c# - 多目标 NuGet 包的错误依赖解析
- c++ - PostMessage:未收到消息
- scala - Spark 结构化流中的窗口长度
- machine-learning - 强化学习是否适用于 RANDOM 环境?
- c# - EF Core:在创建新对象期间“重新获取”实体以访问 FK 对象的最优化方法是什么?
- ionic-framework - Ionic 4 滚动时隐藏工具栏
- scala - Any和_有什么区别
- android - 某些手机中未显示 Toast 通知