15

如何将空格分隔的整数输入转换为整数列表?

示例输入:

list1 = list(input("Enter the unfriendly numbers: "))

转换示例:

['1', '2', '3', '4', '5']  to  [1, 2, 3, 4, 5]
4

7 回答 7

35

map()是你的朋友,它将作为第一个参数给出的函数应用于列表中的所有项目。

map(int, yourlist) 

因为它映射了每个可迭代对象,您甚至可以执行以下操作:

map(int, input("Enter the unfriendly numbers: "))

其中(在 python3.x 中)返回一个地图对象,可以将其转换为列表。我假设您使用的是 python3,因为您使用的是input,而不是raw_input.

于 2012-04-27T13:47:27.477 回答
15

一种方法是使用列表推导:

intlist = [int(x) for x in stringlist]
于 2012-04-27T13:48:12.437 回答
3

这有效:

nums = [int(x) for x in intstringlist]
于 2012-04-27T14:46:10.860 回答
1

你可以试试:

x = [int(n) for n in x]
于 2012-04-27T13:48:05.790 回答
1

Say there is a list of strings named list_of_strings and output is list of integers named list_of_int. map function is a builtin python function which can be used for this operation.

'''Python 2.7'''
list_of_strings = ['11','12','13']
list_of_int = map(int,list_of_strings)
print list_of_int 
于 2017-05-22T05:40:36.050 回答
0
 l=['1','2','3','4','5']

for i in range(0,len(l)):
    l[i]=int(l[i])
于 2012-04-27T15:46:10.480 回答
-1

只是好奇你得到'1','2','3','4'而不是1、2、3、4的方式。无论如何。

>>> list1 = list(input("Enter the unfriendly numbers: "))
Enter the unfriendly numbers: 1, 2, 3, 4
>>> list1 = list(input("Enter the unfriendly numbers: "))
Enter the unfriendly numbers: [1, 2, 3, 4]
>>> list1
[1, 2, 3, 4]
>>> list1 = list(input("Enter the unfriendly numbers: "))
Enter the unfriendly numbers: '1234'
>>> list1 = list(input("Enter the unfriendly numbers: ")) 
Enter the unfriendly numbers: '1', '2', '3', '4'
>>> list1
['1', '2', '3', '4']

好的,一些代码

>>> list1 = input("Enter the unfriendly numbers: ")
Enter the unfriendly numbers: map(int, ['1', '2', '3', '4'])
>>> list1
[1, 2, 3, 4]
于 2012-04-27T13:51:30.420 回答