将用户输入到列表中
我正在尝试接收用户输入,然后将其放入列表中。我有一个工作版本,但是,我觉得它好像是多余的(第一个块似乎是多余的,但如果我把它拿走,它就不起作用)。有什么办法可以改善这种情况吗? 感谢
def pastChoice():
choice = raw_input("> ")
prevMove = []
prevMove.append(choice)
for i in prevMove:
choice = raw_input("> ")
prevMove.append(choice)
print prevMove
PastChoice()
我正在制作一个游戏,我想向用户展示他们已经做出的选择。
前任。如果您想查看以前的选择,请输入“history”
['a','a','c','b']
I am trying to receive user input and then put it into a list. I have a working version, however, I feel as though it is redundant(the first block seems redundant, though if I take it away, it doesn't work). Any way this can be improved?
Thanks
def pastChoice():
choice = raw_input("> ")
prevMove = []
prevMove.append(choice)
for i in prevMove:
choice = raw_input("> ")
prevMove.append(choice)
print prevMove
pastChoice()
I am making a game and I want to show the user what choices they have already made.
Ex. Type 'history' if you would like to see previous choices
['a','a','c','b']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定您对此代码的意图,但这大致相同:
块:
要求用户输入并将其附加到 prevMove,因此在循环开始时,条件
i in prevMove
评估 < code>i 到prevMove
中的第一个元素,然后因为在第二个块中您将新元素附加到prevMove
,所以迭代会继续对新元素进行迭代附加元素和循环永远不会结束。如果删除第一个块,但保留
for
循环,则它将不起作用,因为prevMove
内没有元素,因此没有可迭代的内容。I'm not sure about your intentions for this code, but this is roughly equivalent:
the block:
asks user for input and appends it to prevMove, so at loop start, the condition
i in prevMove
evaluatesi
to the first element inprevMove
, then because in the second block you're appending new elements toprevMove
, the iteration continues over those the newly appended elements and the loop never ends.If you remove the first block, but keep the
for
loop, it won't work because there are no elements insideprevMove
and therefore nothing to iterate over.你可以这样做吗?我不知道你尝试这样做的真正原因,但是接受用户输入并添加到列表中就可以了。
编辑:
由于问题编辑,代码现在将记录事件的历史记录并具有获取它们的功能。
you could do it this way? I don't know the real reason you are trying to do this, but to accept user input and add to a list this will do fine.
EDIT:
Due to Questions edit, the code will now record the history of events and have a function to obtain them.