如何创建程序以提示用户输入列表,然后让程序反转列表并为用户打印

时间:2014-02-11 00:52:44

标签: python reverse

如何创建程序以提示用户输入列表,然后让程序反转列表并为用户打印。这种反转需要是手动的,而不是使用reverse()函数。到目前为止,我有......

def main():
    print("This program will reverse your list!")
    list = []
    userlist = input( "Enter your list:")
    list.append(userlist) 
    reverselist = userlist[::-1]
    print("Your list in reverse is: ", reverselist)
    input ("Press enter to close program")
main()

它可以工作,但它不会保留一个列表,它更像是一个字符串。如果你进入苹果香蕉,就会吐出ananab elppa。

4 个答案:

答案 0 :(得分:1)

def main():
    print("This program will reverse your list!")

    # get a list of strings
    items = []
    while True:
        s = input("Next item (or <Enter> to quit): ")
        if s:
            items.append(s)
        else:
            break

    # make a reversed copy of the list
    items_len = len(items)
    smeti = [0] * items_len
    for i,val in enumerate(items)
        smeti[items_len - i - 1] = val

    print("Your list in reverse is: {}".format(smeti))
    input("Press enter to close program")

if __name__=="__main__":
    main()

答案 1 :(得分:0)

您通过执行userlist[::-1]来反转字符串,这就是为banana读取ananab的原因。如果用空格分割并反转单词,你真正应该做些什么。

尝试更改:

userlist = input( "Enter your list:")
list.append(userlist) 
reverselist = userlist[::-1]

为:

userlist = input( "Enter your list:")
reverselist = " ".join(reversed(userlist.split()))    

答案 2 :(得分:0)

用于反转列表的有用“手动”习惯是while循环:

>>> li
[0, 1, 2, 3, 4]
>>> il=[]
>>> while li:
...    il.append(li.pop())
... 
>>> il
[4, 3, 2, 1, 0]

所以你的计划是:

def main():
    print("This program will reverse your list!")
    userlist = input( "Enter your list separated by spaces:")
    li=userlist.split()
    reverselist=[]
    while li:
        reverselist.append(li.pop())
    print("Your list in reverse is: ", reverselist)

main()

运行时:

This program will reverse your list!
Enter your list separated by spaces:apple banana peach
Your list in reverse is:  ['peach', 'banana', 'apple']

答案 3 :(得分:0)

list = []
def reverselyst(list):
    print ("Please enter list values one after the other or press space to stop:")
    while True:
        userinput = input()
        if userinput != ' ':
            list.append(userinput)
        else:
            print (list)
            break
    print("the reverse of list is" + str(list[-1: :-1]))
reverselyst(list)