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

Shr*_*ram 13 python integer input list

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

输入示例:

list1 = list(input("Enter the unfriendly numbers: "))
Run Code Online (Sandbox Code Playgroud)

转换示例:

['1', '2', '3', '4', '5']  to  [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

ch3*_*3ka 32

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

map(int, yourlist) 
Run Code Online (Sandbox Code Playgroud)

因为它映射每个可迭代的,你甚至可以做:

map(int, input("Enter the unfriendly numbers: "))
Run Code Online (Sandbox Code Playgroud)

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


Mae*_*ler 14

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

intlist = [int(x) for x in stringlist]
Run Code Online (Sandbox Code Playgroud)