我有一根绳子"42 0"
(例如)并且需要获取两个整数的数组。我可以做一个.split
在一个空间上?
The obvious approach to this problem is a common combination of simple tasks:
- How do I split a string into a list of words? https://stackoverflow.com/questions/743806
- How do I parse a string to a float or int? https://stackoverflow.com/questions/379906
- How can I collect the results of a repeated calculation in a list, dictionary etc. (or make a copy of a list with each element modified)? https://stackoverflow.com/questions/75666408
However, depending on the exact requirements, it can be addressed in other ways. For some cases, the split step may be sufficient on its own. There are other approaches, given in some answers here, to produce different output besides a native Python list
- for example, using the standard library array.array
, or a Numpy array.
Alternately, the problem can be seen as a special case of How to extract numbers from a string in Python? https://stackoverflow.com/questions/4289331 .
Use str.split() https://docs.python.org/library/stdtypes.html#str.split:
>>> "42 0".split() # or .split(" ")
['42', '0']
注意str.split(" ")
在这种情况下是相同的,但如果一行中有多个空格,则行为会有所不同。还有,.split()
分割所有空白,而不仅仅是空格。
Using map
当您想要将可迭代项转换为内置项时,通常看起来比使用列表推导式更干净,例如int
, float
, str
等。在 Python 2 中:
>>> map(int, "42 0".split())
[42, 0]
在Python 3中,map
将返回一个惰性对象。您可以将其放入列表中list()
:
>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)