将字符串列表转换为整数列表 [英] converting list of string to list of integer

查看:636
本文介绍了将字符串列表转换为整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I convert a space separated integer input into a list of integers?

示例输入:

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

转换示例:

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


推荐答案

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

map() is your friend, it applies the function given as first argument to all items in the list.

map(int, yourlist) 

因为它映射每次迭代,你甚至可以这样做:

since it maps every iterable, you can even do:

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

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

which (in python3.x) returns a map object, which can be converted to a list. I assume you are on python3, since you used input, not raw_input.

这篇关于将字符串列表转换为整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆