0

I have a list that looks like this: ['1 0 0','2 0.5 0.25','3 1 0.5','4 1.5 0.75']

I want to end up with these three arrays: [1,2,3,4] and [0,0.5,1,1.5] and [0,0.25,0.5,0.75]

i.e. I want the first value of each list item and store it in an array, and do the same with the second and third values.

I tried this

for i in coordinates[:]:
    number,x,y=i.split(' ')

also tried using number[] and number.append but none of these seem to work

0

4 Answers 4

6

This can be done as follows:

list(zip(*(list(map(float, s.split())) for s in coordinates)))

First we loop through all strings in the list and split them

[s.split() for s in coordinates]

Then we map the float function over all the individual strings to convert them to floats:

[list(map(float, s.split())) for s in coordinates]

Then we use zip to get them the way you want them.

Sign up to request clarification or add additional context in comments.

Comments

2

Similar to @ikkuh's but with "configurable" types:

data = ['1 0 0','2 0.5 0.25','3 1 0.5','4 1.5 0.75']
tp = [int, float, float] 

parsed = ((t(j) for t, j in zip(tp, record.split())) for record in data)
idx, x, y = (list(i) for i in zip(*parsed))
idx
# [1, 2, 3, 4]
x
# [0.0, 0.5, 1.0, 1.5]
y
# [0.0, 0.25, 0.5, 0.75]

4 Comments

Python 2 version: map(map, tp, zip(*map(str.split, data))). Not sure I ever mapped map before :-)
@StefanPochmann Gosh, that does qualify as unreadable. Transposing first looks like a good idea btw.
Well, I think it's quite readable. But yeah, one reason I didn't post it as answer is that I'm not in the mood for explaining it :-P
@StefanPochmann It's the nested maps where I - or rather my spinning head - draw the line.
1

Creating three new list, and going through a input:

input = ['1 0 0','2 0.5 0.25','3 1 0.5','4 1.5 0.75']
x_list = []
y_list = []
z_list = []

for i in input:
    x, y, z = i.split(' ')
    x_list.append(x)
    y_list.append(y)
    z_list.append(z)

Comments

0

Here is one approach without for loop , using lambda :

a=['1 0 0','2 0.5 0.25','3 1 0.5','4 1.5 0.75']

print(list(zip(*list((map(lambda y:y.split(),a))))))

output:

[('1', '2', '3', '4'), ('0', '0.5', '1', '1.5'), ('0', '0.25', '0.5', '0.75')]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.