如何将一串空格分隔的数字拆分为整数? [英] How to split a string of space separated numbers into integers?

查看:28
本文介绍了如何将一串空格分隔的数字拆分为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串 "42 0" (例如)并且需要获取两个整数的数组.我可以在空间上做一个 .split 吗?

解决方案

使用 <代码>str.split():

<预><代码>>>>"42 0".split() # 或 .split(" ")['42', '0']

请注意,str.split(" ") 在这种情况下是相同的,但如果一行中有多个空格,则行为会有所不同.同样,.split() 拆分所有空白,而不仅仅是空格.

使用 map 通常看起来比使用列表推导式更简洁,当您想将可迭代项转换为诸如 intfloat 之类的内置函数时、str 等.在 Python 2 中:

<预><代码>>>>地图(整数,42 0".split())[42, 0]

在 Python 3 中,map 将返回一个惰性对象.您可以使用 list() 将其放入列表:

<预><代码>>>>地图(整数,42 0".split())<映射对象在 0x7f92e07f8940>>>>列表(地图(int,42 0".split()))[42, 0]

I have a string "42 0" (for example) and need to get an array of the two integers. Can I do a .split on a space?

解决方案

Use str.split():

>>> "42 0".split()  # or .split(" ")
['42', '0']

Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.

Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:

>>> map(int, "42 0".split())
[42, 0]

In Python 3, map will return a lazy object. You can get it into a list with list():

>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]

这篇关于如何将一串空格分隔的数字拆分为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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