我有一个字符串如下
144.963286 -37.814212 144.964498 -37.813854 144.964962 -37.814806 144.963711, -37.815168
我想将上述字符串转换为如下数组:
[(144.963286, -37.814212), (144.964498, -37.813854), (144.964962, -37.814806), (144.963711, -37.815168)]
答案 0 :(得分:4)
假设您使用点号将小数部分与小数部分分开(并且不需要逗号),
zip
成对浮动。喜欢
npm install --save joi
正如@AlexanderReynolds所建议的那样,对于参数数量奇特且带有某种>>> string = '144.963286 -37.814212 144.964498 -37.813854 144.964962 -37.814806 144.963711, -37.815168'
>>> floats = map(float, string.replace(',', '').split()) # use `itertools.imap` instead of `map` in Python2
>>> list(zip(floats, floats))
[(144.963286, -37.814212), (144.964498, -37.813854), (144.964962, -37.814806), (144.963711, -37.815168)]
(默认值为zip
)的情况,我们可以使用itertools.zip_longest
function而不是fillvalue
>
None
我们也可以使用itertools.repeat
这样的一行(虽然很复杂)来完成它
>>> string = '144.963286, -37.814212 42'
>>> floats = map(float, string.replace(',', '').split())
>>> from itertools import zip_longest
>>> list(zip_longest(floats, floats,
fillvalue=float('inf')))
[(144.963286, -37.814212), (42.0, inf)]
答案 1 :(得分:2)
使用zip
进行切片:
s = '144.963286 -37.814212 144.964498 -37.813854 144.964962 -37.814806 144.963711 -37.815168'
splitted = s.split()
result = list(zip(splitted[::2], splitted[1::2]))
# [('144.963286', '-37.814212'), ('144.964498', '-37.813854'), ('144.964962', '-37.814806'), ('144.963711', '-37.815168')]
答案 2 :(得分:0)
您可以使用正则表达式:
import re
s = '144.963286 -37.814212 144.964498 -37.813854 144.964962 -37.814806 144.963711, -37.815168'
pattern = r'(-?\d+\.\d+).+?(-?\d+\.\d+)'
new_s = [(float(i.group(1)), float(i.group(2))) for i in re.finditer(pattern, s)]
# [(144.963286, -37.814212), (144.964498, -37.813854), (144.964962, -37.814806), (144.963711, -37.815168)]