简体   繁体   English

如何将用户输入存储到列表中?

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

For example if I have a user input called num : 例如,如果我有一个名为num的用户输入:

num = int(input('Enter numbers'))

I want to be able to store these numbers into a list to be manipulated. 我希望能够将这些数字存储到要操作的列表中。 How can I go about this? 我该怎么办? Thanks. 谢谢。

The prompt "Enter numbers" suggests that the user will enter several numbers on the one line, so split the line and convert each number to an int . 提示“输入数字”建议用户在一行上输入多个数字,因此请拆分该行并将每个数字转换为int This list comprehension is a convenient way to do it: 这种列表理解是一种方便的方法:

numbers = [int(n) for n in input('Enter numbers: ').split()]

The above is for Python 3. For Python 2, use raw_input() instead: 上面是针对Python 3的。对于Python 2,请使用raw_input()

numbers = [int(n) for n in raw_input('Enter numbers: ').split()]

In either case: 在任一情况下:

>>> numbers = [int(n) for n in raw_input('Enter numbers: ').split()]
Enter numbers: 1 2 3 4 5
>>> numbers
[1, 2, 3, 4, 5]
input_numbers = raw_input("Enter numbers divided by spaces")

input_numbers_list = [int(n) for n in input_numbers.split()]

print input_numbers_list

you can do it in a single line by using functional programming construct of python called map, 您可以使用称为map的python的函数式编程结构,在一行中完成此操作,

python2 python2

input_list = map(int, raw_input().split())

python3 python3

input_list = map(int, input().split())

input: 输入:

list_of_inputs = input("Write numbers: ").split() 
#.split() will split the inputted numbers and convert it into a list 
list_of_inputs= list(map(int , list_of_inputs))
#as the inputted numbers will be saved as a string. This code will convert the string into integers

output: 输出:

Write numbers: 43 5 78
>>> print (list_of_inputs)
[43, 5, 78]

i am using python 3.6 我正在使用python 3.6

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

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