我想一遍又一遍地提示用户输入短语列表,直到他们输入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"):
答案 0 :(得分:4)
您只需使用iter(input, 'END')
即可返回callable_iterator
。然后我们可以使用list()
来获取真实的列表:
>>> 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']
答案 1 :(得分:2)
一种方法是使用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']