简体   繁体   English

如何将用户输入转换为列表?

[英]How do I convert user input into a list?

I'm wondering how to take user input and make a list of every character in it.我想知道如何获取用户输入并列出其中的每个字符。

magicInput = input('Type here: ')

And say you entered "python rocks" I want a to make it a list something like this并假设您输入了“蟒蛇岩石”,我想将其设为类似这样的列表

magicList = [p,y,t,h,o,n, ,r,o,c,k,s]

But if I do this:但如果我这样做:

magicInput = input('Type here: ')
magicList = [magicInput]

The magicList is just魔术列表只是

['python rocks']

Use the built-in list() function:使用内置的list()函数:

magicInput = input('Type here: ')
magicList = list(magicInput)
print(magicList)

Output输出

['p', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'o', 'c', 'k', 's']

gtlamber is right. gtlamber 是对的。 But you don't need actualy to do anyting as the string has most of the list interface (means that you can treat string as a list).但是您实际上不需要做任何事情,因为字符串具有大部分列表接口(意味着您可以将字符串视为列表)。 You can do for instance:例如,您可以执行以下操作:

print(magicInput[1])
print(magicInput[2:4])

Output:输出:

'y'
'th'

Another simple way would be to traverse the input and construct a list taking each letter另一种简单的方法是遍历输入并构造一个包含每个字母的列表

magicInput = input('Type here: ')
list_magicInput = []
for letter in magicInput:
    list_magicInput.append(letter)

or you can simply do或者你可以简单地做

x=list(input('Thats the input: ')

and it converts the thing you typed it as a list并将您输入的内容转换为列表

a=list(input()).

它将输入转换为列表,就像我们要将输入转换为整数一样。

a=(int(input())) #typecasts input to int

using list comprehension,使用列表理解,

x = [_ for _ in input()]
print(x)

produces产生

python rocks
['p', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'o', 'c', 'k', 's']

[Program finished] 

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

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