简体   繁体   English

将多个用户输入追加到列表

[英]Appending multiple user inputs to a list

I would like to know how I can take multiple user inputs and append each input to a list. 我想知道如何接受多个用户输入并将每个输入附加到列表中。 For example, the user is asked how many times they would like to send a message. 例如,询问用户要发送消息多少次。 If they specify 3, then they are presented with three inputs which are later appended to the list. 如果它们指定为3,则将为它们提供三个输入,这些输入随后会附加到列表中。

I have tried several different ways to do this however I only ever see the last input appended to the list rather than the multiple inputs. 我尝试了几种不同的方法来执行此操作,但是我只看到最后输入追加到列表中,而不是多个输入。

List = []
total = (int(input('How many?: ')))
for _ in range(total):
    messages = input('> ')
List.append(messages)

print (List)

You did great actually, just need to indent List.append(messages) to include it in the loop code, otherwise you'll be appending the last message only to the list or (in the worst scenario where total is 0) you'll get a not defined error . 您实际上做得很好,只需缩进List.append(messages)以将其包含在循环代码中,否则,您将仅将最后一条消息追加到列表中,或者(在总计为0的最坏情况下)得到一个未定义的错误

List = []
total = (int(input('How many?: ')))
for _ in range(total):
    messages = input('> ')
    List.append(messages)

print (List)
n = input('How many?: ')
l = [raw_input('> ') for i in range(n)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM