例如,如果我有一个用户输入的被叫num
:如何将用户输入存储到列表中?
num = int(input('Enter numbers'))
我希望能够将这些号码存储到被操纵的列表。 我该如何解决这个问题?谢谢。
例如,如果我有一个用户输入的被叫num
:如何将用户输入存储到列表中?
num = int(input('Enter numbers'))
我希望能够将这些号码存储到被操纵的列表。 我该如何解决这个问题?谢谢。
提示“输入数字”表示用户将在一行中输入多个数字,因此拆分该行并将每个数字转换为int
。这个列表解析是做到这一点的快捷方法:
numbers = [int(n) for n in input('Enter numbers: ').split()]
以上是Python 3的对于Python 2,使用raw_input()
代替:
numbers = [int(n) for n in raw_input('Enter numbers: ').split()]
在两种情况下:
>>> 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
你可以使用python函数式编程构造函数在一行中做到这一点,称为map,
python2
input_list = map(int, raw_input().split())
python3
input_list = map(int, input().split())
输入:
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
输出:
Write numbers: 43 5 78
>>> print (list_of_inputs)
[43, 5, 78]
我是我们ing python 3.6
这会得到一个数字。 – 2015-04-04 04:21:38
定义'L = []'然后'为我在范围内(5):L.append(int(input('Enter numbers')))' – 2015-04-04 04:23:51
数字是如何分隔的?像1234或1 2 3 4 – Hackaholic 2015-04-04 04:28:22