python - 通过用户输入删除列表中的值(Python)
问题描述
第一次发帖,我对编程很陌生,(所以请放轻松)虽然我曾在 IT 行业担任帮助台技术员和现场工程师。
我在大学的第一年,并被要求在程序中添加一个部分,以允许用户删除他们输入到列表中的条目。
这是我的代码。
values = []
def programMenu():
print('This program will accept values until 0 is entered.')
choice = continueChoice()
if choice == 'Y':
ages = collectValues()
print('There are ', len(values),' in the data set.')
print('The values are as follows:', end ='')
print(values)
else:
return
def continueChoice():
print('Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
print(choice)
while choice != 'Y' and choice != 'N':
print('Invalid option. Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
return choice
def collectValues():
values = []
while True:
print ('Please enter each value:', end ="")
valValue = (int(input()))
if (valValue ==0):
break
values.append(valValue)
return values
def removeValues():
print(values)
print('Would you like to delete any entries?')
reage = str(input()).upper()
while reage == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
values.remove(delVal)
else:
programMenu()
programMenu()
removeValues()
我已经尝试解决这个问题两天了,但是我收到一个错误“ValueError:list.remove(x):x 不在列表中”我尝试在操作结束时编写 removeValues 代码来添加值,我有试图移动 values = [] 调用等,但没有运气。
我检查了 removeValues 定义实际上是通过编辑来获取输入,以使程序打印用户输入的值,他们希望被删除并且有效。
感谢您的帮助,我只编写了几个月的代码,我已经给我的讲师发了电子邮件,但是在大学人手不足的那一刻,世界上正在发生的事情。
提前致谢。
解决方案
在从列表中删除值之前,您需要添加一个 if 条件来检查列表中是否存在值,例如:
if delVal in values:
values.remove(delVal)
else:
print('Value Not Found in the list')
并且您的 while 循环处于无限循环中,因为 reage = 'Y' 的值并且您没有在循环内将其更改为停止。
您可以使用 if 语句代替 while。
def removeValues():
print(values)
print('Would you like to delete any entries?')
reage = str(input()).upper()
# if reage == 'Y'
if reage == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
# check if delVal is present in the list or not
if delVal in values:
values.remove(delVal)
print('Deleted Age : '+ str(delVal))
print(values)
# if not then print the msg.
else:
print(str(delVal)+' Not Found in the list: ',str(values))
# you can uncomment the below code to again call removeValues function to ask for correct value to delete
#removeValues()
# if reage is not equal to 'Y' then it calls the programMenu again.
else:
programMenu()
推荐阅读
- html - 是否可以使用 CSS 设置占位符伪元素文本?
- python - Django:如何通过编辑迁移文件将初始数据放入数据库?
- angular - Dart Angular Route Parameters not working
- r - 对列表的每个矩阵使用 lapply
- arrays - Count words in list of strings based on words array and making dictionary from it
- flutter - 如何设计高级工具提示(帮助)?
- c# - 不能对特定控件使用调用
- android - 如何修复“找不到工具链文件”“CMake 错误:未设置 CMAKE_C_COMPILER,在 EnableLanguage 之后”cmake libjpeg-turbo.so?
- java - Spring项目中无法配置Swagger,获取File not found异常
- git - 如何更改 git commit 消息内容类型?