与列表的换行符

时间:2015-02-23 00:45:09

标签: python python-3.x

我有一个工作脚本,但它不能按我希望的方式工作:

print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
    myInput = input()
    if myInput == "nothing":
        print('There are ' + str(len(basket)) + ' items in the basket: '+ str(basket))
        break
    else:
        basket.append(myInput)
        print('Okay, what else?')

最后一行应该是这样的:

There are 3 items in the basket: 
Item 1: a sandwich
Item 2: two cans of Dr Pepper
Item 3: some napkins

有什么建议吗?

3 个答案:

答案 0 :(得分:4)

使用enumerate,起始索引为1,str.format

while True:
    myInput = input()
    if myInput == "nothing":
        print('There are {} items in the basket: '.format(len(basket)))
        for ind, item in enumerate(basket,1):
            print("Item{}: {} ".format(ind,item))
        break
    else:
        basket.append(myInput)
        print('Okay, what else?')

你也可以使用列表理解和iter而不需要while循环,它会一直循环,直到用户输入sentinel"nothing"

print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = [ line for line in iter(lambda:input("Please enter an item to add"), "nothing")]

print('There are {} items in the basket: '.format(len(basket)))
for ind,item in enumerate(basket,1):
    print("Item{}: {} ".format(ind,item))

答案 1 :(得分:2)

我认为最好将收集输入和打印结果分开如下:

print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')

basket = []

while True:
    myInput = input()
    if myInput == "nothing":       
        break
    else:
        basket.append(myInput)
        print('Okay, what else?')

print('There are ' + str(len(basket)) + ' items in the basket: ')
for i,item in enumerate(basket):
    print("Item {}: {}".format(i+1, item))

答案 2 :(得分:-1)

空字符串(只是一个回车)仍将被视为一个项目,即使没有任何内容,这将导致您的购物篮中的项目数量不正确,并打印一个空的项目行。考虑捕获并忽略它,或者可能使它等同于第二个if语句中的“nothing”作为中断条件的一部分。

print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
    myInput = input()
    if myInput == "":
        continue
    if myInput == "nothing":
        print('There are ' + str(len(basket)) + ' items in the basket:')
        for itemno, item in enumerate(basket):
            print("Item {0}: {1}".format(itemno+1,item))
        break
    else:
        basket.append(myInput)
        print('Okay, what else?')