简体   繁体   English

在循环python中从用户获取字符串列表作为输入

[英]Get a list of string as input from user in loop python

I am new to python, this is a basic question我是 python 新手,这是一个基本问题

How do you get a list of string as input from the user?你如何从用户那里得到一个字符串列表作为输入? I tried:我试过:

array = []
for i in range(0,4):
    array[i] = input("Enter string")

This has an error.这有一个错误。 I know I am wrong.我知道我错了。 How do we get a list of strings as input?我们如何获取字符串列表作为输入?

Your array has size 0, this is why you can't access any elements (or assign to them).您的数组大小为 0,这就是您无法访问任何元素(或分配给它们)的原因。 The correct code would be:正确的代码是:

array = []
for i in range(4):
    array.append(input("Enter string"))

Try this:尝试这个:

for i in range(4):
    array.append(input("Enter string >>"))

Since your array doesn't have any values yet, assigning to array[i] would not work.由于您的数组还没有任何值,因此分配给array[i]将不起作用。

简洁的:

array = [input("Enter string: ") for i in range(4)]

when range limit is unknown ie, when (n) needs to be taken as an input from the user,当范围限制未知时,即当 (n) 需要作为用户的输入时,

n = int(input("Enter the number of names in list for input:"))
a = [input() for i in range(n)]

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

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