gpt4 book ai didi

python - 列表换行符

转载 作者:太空宇宙 更新时间:2023-11-04 08:57:51 27 4
gpt4 key购买 nike

我有一个可以工作的脚本,但它没有按照我想要的方式工作:

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

有什么建议吗?

最佳答案

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

关于python - 列表换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28665356/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com