如何将空格分隔的整数输入转换为整数列表?
示例输入:
list1 = list(input("Enter the unfriendly numbers: "))
转换示例:
['1', '2', '3', '4', '5'] to [1, 2, 3, 4, 5]
map()
是你的朋友,它将作为第一个参数给出的函数应用于列表中的所有项目。
map(int, yourlist)
因为它映射了每个可迭代对象,您甚至可以执行以下操作:
map(int, input("Enter the unfriendly numbers: "))
其中(在 python3.x 中)返回一个地图对象,可以将其转换为列表。我假设您使用的是 python3,因为您使用的是input
,而不是raw_input
.
一种方法是使用列表推导:
intlist = [int(x) for x in stringlist]
这有效:
nums = [int(x) for x in intstringlist]
你可以试试:
x = [int(n) for n in x]
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
l=['1','2','3','4','5']
for i in range(0,len(l)):
l[i]=int(l[i])
只是好奇你得到'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]