将字符串列表转换为整数列表

16
如何将以空格分隔的整数输入转换为整数列表?
示例输入:
list1 = list(input("Enter the unfriendly numbers: "))

示例转换:

['1', '2', '3', '4', '5']  to  [1, 2, 3, 4, 5]
7个回答

35

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

map(int, yourlist) 

由于它映射到每个可迭代对象,所以您甚至可以执行以下操作:

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

在Python3.x中,map函数返回一个映射对象,可以将其转换为列表。 我假设您正在使用Python3,因为您使用了input而不是raw_input


1
+1 但是您是不是想使用 map(int,yourlist) - Rob I
你是指map(int, input().split()),还是Python3自动将空格分隔的输入转换为列表? - quodlibetor
不,我假设数字是没有空格输入的,因为提供的示例表明了这一点。实际上,我并没有将其发布为解决方案,我只是想指出map()的第二个参数不一定是列表,任何可迭代对象都可以。 - ch3ka

15

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

intlist = [int(x) for x in stringlist]

+1,[int(x) for x in input().split()] 以符合 OP 的规格。 - georg

3

这个有效:

nums = [int(x) for x in intstringlist]

1

您可以尝试以下方法:

x = [int(n) for n in x]

3
这个不起作用。int 不是字符串的一个方法。 - Matt Fenwick
抱歉,我编辑了一下...这才是我的本意 :) - Silviu
这不是错误的,但我通常不会像那样重复使用 x - Matt Fenwick
你能给我一个为什么的例子吗? - Silviu

1

假设有一个名为list_of_strings的字符串列表,输出是一个名为list_of_int的整数列表。 map函数是Python内置函数,可用于此操作。

'''Python 2.7'''
list_of_strings = ['11','12','13']
list_of_int = map(int,list_of_strings)
print list_of_int 

0
 l=['1','2','3','4','5']

for i in range(0,len(l)):
    l[i]=int(l[i])

-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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接