带列表的换行符

2024-10-06 12:54:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

有什么建议吗?你知道吗


Tags: thetoinyouasitemsitemare
3条回答

使用起始索引为1的enumeratestr.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))

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

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))

空字符串(仅回车)仍将被视为项目,即使没有任何内容,这将导致篮子中的项目不正确,并打印空项目行。考虑捕获它并忽略它,或者作为break条件的一部分,在第二个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?')

相关问题 更多 >