[英]Saving User Inputs into a List in Python 3.5.1
I want to prompt the user for a list of phrases over and over again until they input END
and save all of the user's inputs into a list. 我想一遍又一遍地提示用户输入短语列表,直到他们输入
END
并将所有用户输入保存到列表中。 How can I do that? 我怎样才能做到这一点?
My code so far: 到目前为止,我的代码:
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"):
You can simply use iter(input, 'END')
, which returns a callable_iterator
. 您可以简单地使用
iter(input, 'END')
,它返回一个callable_iterator
。 Then we can use list()
to get a real list: 然后我们可以使用
list()
获得真实列表:
>>> l = list(iter(input, 'END'))
foo
bar
foobar
END
>>> l
['foo', 'bar', 'foobar']
About how does it work, if you take a look at help(iter)
: 关于它是如何工作的,如果您查看
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.
You can also use a while
loop if you think it's more simple and clear anyway: 如果您认为它更简单明了,也可以使用
while
循环:
l = []
while True:
password = input()
if password != 'END':
l.append(password)
else:
break
Demo: 演示:
>>> l = []
>>> while True:
... password = input()
... if password != 'END':
... l.append(password)
... else:
... break
...
...
...
foo
bar
END
>>> l
['foo', 'bar']
One way to do is with a while loop
: 一种方法是使用
while loop
:
phraseList = []
phrase = input('Please enter a phrase: ')
while phrase != 'END':
phraseList.append(phrase)
phrase = input('Please enter a phrase: ')
print(phraseList)
Result: 结果:
>>> 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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.