将用户输入保存到列表中 Python 3.5.1

Saving User Inputs into a List in Python 3.5.1

我想一遍又一遍地提示用户输入短语列表,直到他们输入 END 并将用户的所有输入保存到列表中。我该怎么做?

到目前为止我的代码:

print("Please input passwords one-by-one for validation.")
userPasswords = str(input("Input END after you've entered your last password.", \n))
boolean = True
while not (userPasswords == "END"):

一种方法是使用 while loop:

phraseList = []

phrase = input('Please enter a phrase: ')

while phrase != 'END':
    phraseList.append(phrase)
    phrase = input('Please enter a phrase: ')

print(phraseList)

结果:

>>> Please enter a phrase: first phrase
>>> Please enter a phrase: another one
>>> Please enter a phrase: one more
>>> Please enter a phrase: END
>>> ['first phrase', 'another one', 'one more']

您可以简单地使用 iter(input, 'END'),其中 returns 一个 callable_iterator。然后我们可以使用 list() 得到一个 real 列表:

>>> l = list(iter(input, 'END'))
foo
bar
foobar
END
>>> l
['foo', 'bar', 'foobar']

关于它是如何工作的,如果你看一下 help(iter):

iter(...)
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator

    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.

你也可以使用while循环,如果你觉得这样更简单明了的话:

l = []
while True:
    password = input()
    if password != 'END':
        l.append(password)
    else:
        break

演示:

>>> l = []
>>> while True:
...     password = input()
...     if password != 'END':
...         l.append(password)
...     else:
...         break
...         
...     
... 
foo
bar
END
>>> l
['foo', 'bar']