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

Python 将字符串列表转换为整数列表,python,list,input,integer,Python,List,Input,Integer,如何将空格分隔的整数输入转换为整数列表 输入示例: list1 = list(input("Enter the unfriendly numbers: ")) 转换示例: ['1', '2', '3', '4', '5'] to [1, 2, 3, 4, 5] map()是您的朋友,它将作为第一个参数给定的函数应用于列表中的所有项 map(int, yourlist) 由于它映射每个iterable,您甚至可以执行以下操作: map(int, input("Enter the unf

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

输入示例:

list1 = list(input("Enter the unfriendly numbers: "))
转换示例:

['1', '2', '3', '4', '5']  to  [1, 2, 3, 4, 5]
map()
是您的朋友,它将作为第一个参数给定的函数应用于列表中的所有项

map(int, yourlist) 
由于它映射每个iterable,您甚至可以执行以下操作:

map(int, input("Enter the unfriendly numbers: "))
它(在python3.x中)返回一个映射对象,可以将其转换为列表。 我假设您使用的是python3,因为您使用的是
input
,而不是
raw\u input

您可以尝试:

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

一种方法是使用列表理解:

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

只是好奇你用“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]
这项工作:

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

假设有一个名为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 

+1但您的意思是
map(int,yourlist)
?您的意思是
map(int,input().split())
,还是py3k会自动将空格分隔的输入转换为列表?不,我假设输入的数字没有空格,如提供的示例所示。事实上,我并没有将此作为解决方案发布,我只是想指出map()的第二个参数不必是列表,任何iterable都可以,但这不起作用
int
不是字符串上的方法。抱歉,我编辑了它。。。这实际上就是我的意思:)这没有错,但我通常不会像那样重复使用
x
。你能给我一个例子吗?+1,
[int(x)for x in input().split()]
,以符合OP的规范。
'''Python 2.7'''
list_of_strings = ['11','12','13']
list_of_int = map(int,list_of_strings)
print list_of_int