Python 如何在while循环中保存列表?

Python 如何在while循环中保存列表?,python,Python,我想让我的while循环在列表中累积项目,但我不知道如何做 这就是我所拥有的: counter = 0 while counter != -1: animal = input("Please enter an animal name (or -1 to quit): ") if animal == "-1": break sound = input("Please enter an animal sound: &

我想让我的while循环在列表中累积项目,但我不知道如何做

这就是我所拥有的:

counter = 0
while counter != -1:
    animal = input("Please enter an animal name (or -1 to quit): ")
    if animal == "-1":
        break

sound = input("Please enter an animal sound: ")
if sound == "-1":
    break
    
grouped = []
animal = [animal]
sound = [sound]
grouped.append(animal, sound)
最后应该是这样的:

[[‘cow’,’moo’],[‘dog’,’woof’],[‘droid’,’beep’]]
试试这个:

result = []
while True:
    animal = input("Please enter an animal name (or -1 to quit): ")
    if animal == "-1":
        break
    sound = input("Please enter an animal sound: ")
    result.append([animal, sound])
    
print(result)

您可以通过将它们读入两个变量
animal
sound
,并检查它们是否为
-1
,来完成此操作。如果它们不是
-1
,则将其附加到
动物中

counter = 0
animals = []
while counter != -1:
    animal = input("Please enter an animal name (or -1 to quit): ")
    sound = input("Please enter an animal sound (or -1 to quit): ")
    if animal == "-1" or sound == "-1":
        break
    else:
      animals.append([animal,sound])

print(animals)
输入

输出

[[‘cow’,’moo’],[‘dog’,’woof’],[‘droid’,’beep’]]

按照你的逻辑,你想在动物列表中加上动物的名字。。每次提供名称后,您都应该将其添加到列表中使用list方法将项目添加到循环中的列表中。您喜欢的
while counter!=-1:
看起来令人困惑,好像它是一个bug,但您可能希望循环只有在到达
break
语句时才会终止。如果这是您的意图,您应该明确地编写
,而True:
,因为这样一来,您的意图就显而易见了。
[[‘cow’,’moo’],[‘dog’,’woof’],[‘droid’,’beep’]]