2017-05-12 21 views
0

我需要创建一个代码,如果你输入1,它会显示你的实际列表,这是空的,然后如果你把2,你就可以添加“x”到列表中,如果你按3你可以在列表中删除,最后一件事是如果你按9,你退出python。我该如何解决这个问题? Python输入列表

下面的代码:

list = [] 
if input == "1": 
    print list 
if input == "2": 
    list.append("hi") 
    print list 
if input == "3": 
    list.remove("hi") 
    print list 
if input == "9": 
    sys.exit() 

I'll很高兴,如果有人可以帮助我。

回答

1

你可以试试这个。 我以为你每次都需要输入,所以有一个无限的while循环{如果我错了,你只想输入一次,那么你可以删除while循环,它也可以正常工作} 。 此外,我想从删除列表中的元素是,你的意思是删除插入列表中的最新元素,所以这段代码将删除插入的最新元素。 此外如果有{1,2,3,9}以外的任何输入,下面的代码将处理它。

希望这能解决您的问题。

import sys 
arr = [] #creates an empty list. 

while True: 

inp = raw_input("Enter the number you want to enter {1,2,3,9} :- ") 

if inp == "1": 
    print arr; 

elif inp == "2": 
    temp = raw_input("Enter what you want to add to the list :- ") 
    arr.append(temp) 
    print arr 

elif inp == "3": 
    arr = arr[:-1] ## will remove the last element , and will also handle even if there is no element present 
    print arr 

elif inp == "9": 
    sys.exit() 

else: #Any input other than {1,2,3,9} 
    print "Please enter the input from {1,2,3,9}" 
0

试试这个。

import sys 
list = [] 
ch = sys.stdin.read(1) 
if ch == "1": 
    print(list) 
if ch == "2": 
    list.append("hi") 
    print(list) 
if ch == "3": 
    list.remove("hi") 
    print(list) 

if ch == "9": 
    sys.exit()