开发者

How to format a string into a two column list

I have a python string in the following format:

"x1 y1\n x2 y2\n x3 y3\n ..."

I would like to transform this into a list points = [p1, p2, p3,..开发者_StackOverflow.], where p1, p2 and p3 are [x1,y1], [x2,y2] and [x3,y3] etc.

Thanks


Think you can use the following:

inputText = "x1 y1\n x2 y2\n x3 y3\n"
print [line.split() for line in inputText.split('\n') if line]


obviously, many ways to do this.

I would use list comprehension for its brevitiy.

>>> str = 'x1 y1\n x2 y2\n x3 y3\n'
>>> [p.split() for p in str.split('\n') if p != ''] 
[['x1', 'y1'], ['x2', 'y2'], ['x3', 'y3']]


points = []
for point in myStr.split('\n'):
    points.append(point.split())


a='x1 y1\n x2 y2\n x3 y3\n'

points = map (lambda x : x.split (), a.split ('\n'))


Would this do?

>>> raw = "x1 y1\nx2 y2\nx3 y3"
>>> lines = raw.split("\n")
>>> points = []
>>> for l in lines:
...     points.append(l.split(' '))
... 
>>> points
[['x1', 'y1'], ['x2', 'y2'], ['x3', 'y3']]
>>>

Split on new lines, then for each line assume a space splits the values, create a list of points from that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜