【问题标题】:How to write a function to edit raw input in an array?如何编写一个函数来编辑数组中的原始输入?
【发布时间】:2015-01-26 18:48:00
【问题描述】:

我正在编写一个程序,它接受用户输入并将其保存在一个数组中。我目前正在尝试编写一个编辑数组中数据的函数。到目前为止,我有:

data = []
user_input = int(raw_input('How many Subject do you wish to add? : '))
for i in range (0, user_input):
    x = raw_input('Enter Subject: ')
    data.append(x)

print(data)

【问题讨论】:

  • 到目前为止,您在尝试编写的函数中做了什么?另外,您要编辑什么?
  • 看来您已成功将数据存储到数组中。您尝试以何种方式编辑数据?
  • 为什么我不能编辑这个问题以使代码可读?编辑按钮是灰色的。
  • 是的,一旦数组被项目填充。我的代码中的下一个函数询问用户是否要编辑保存在数组中的任何项目。到目前为止,我已经编写了这样的代码: yes = 1 no = 2 print "would you like to add/remove any items in list" print "1: yes" print "2: no" edit_input = int(raw_input('choose?: ' )) 如果edit_input == 1:打印(数据)
  • @W0rmSp17 请粘贴您的整个代码..

标签: python arrays python-3.x edit


【解决方案1】:

据我了解,我为您准备了此代码。

data = []
user_input = int(raw_input('How many Subject do you wish to add? : '))
for i in range (0, user_input):
    x = raw_input('Enter Subject: ')
    data.append(x)

print(data)
yes = 1
no = 2
print "would you like to add/remove any items in list"
print "1: yes"
print "2: no"
edit_input = int(raw_input('choose?: '))
if edit_input == 1:
    edit_data = raw_input('Enter few more Subjects: ')
    data.append(edit_data)
else:
    edit_data = raw_input('Enter Subjects you want to remove: ')
    if edit_data in data:
        data.remove(edit_data)
    else:
        print "element not found"
print data

【讨论】:

  • 谢谢你这是我需要的:)
  • 当用户不理解需要输入一个int而输入"two"时会发生什么?还是直接回车?
  • @Neftas 可以处理这些条件。你可以使用dict 两个用它的单词映射数字。 tryexcept 或简单的 if/elif 条件也会来救援。我讨厌免费编写智能代码:P,所以我只是进行了必要的更改以获得 OP 的要求。
【解决方案2】:
data = []
user_input = int(raw_input('How many Subject do you wish to add? : ')) 

for i in range (0, user_input): 
    x = raw_input('Enter Subject: ') 
    data.append(x) 

while True:
    print ("would you like to add/remove any items in list")
    print ("1: yes")
    print ("2: remove")
    print ("3: exit")
    edit_input = int(raw_input('choose?: '))
    if edit_input == 1:
        edit_data = raw_input('Enter a new Subject: ')
        data.append(edit_data)
    elif edit_input == 2:
        edit_data = raw_input('Enter a Subject you want to remove: ')
        if edit_data in data:
            data.remove(edit_data)
        else:
            print('Subject not found!')
    else:
        # breaking off the loop here
        break

print data

【讨论】:

  • @DineshPanchananam 您是否真的尝试运行此代码? if user_input == ""总是将是False,因为int 类型的变量永远不能是空字符串(所以如果用户只需在第一个提示符下按 Enter 或输入类似 two) 的内容。如果要检查用户输入,请使用 try ... except 构造。
  • @Neftas:真的,谢谢。
猜你喜欢
  • 2021-10-23
  • 2013-03-21
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2022-12-07
  • 2011-02-07
相关资源
最近更新 更多