python - How do you change a one dimensional list into two dimensional using existing elements? -
python - How do you change a one dimensional list into two dimensional using existing elements? -
this question has reply here:
how split list evenly sized chunks in python? 45 answersi reading in text file containing several lists each on own line. elements in given list non-integer x,y co-ordinates need placed array such that:
[x1, y1, x2, y2, x3, y3,....xn, yn]
becomes:
x1 x2 x3....xn
y1 y2 y3....yn
but in same 2d array.
i'm new coding , have tried various methods no avail. right looping on number of co-ordinate pairs , trying append values within loop unsure how this.
this how have started it:
with open('textfile.txt', 'r') infile: line in infile: array=[] number=(line.count(" ")+1)/2 #number of x,y pairs in list in range(0, number-1):
now don't know go here help appreciated! thanks
since new python , dealing numerical data, may want consider de facto standard module such manipulations, numpy
. it, problem becomes trivial:
import numpy np = [1,2,3,4,5,6,7,8] print np.array(a).reshape((len(a)/2,2)).t >>> [[1 3 5 7] [2 4 6 8]]
here cast list in numpy array np.array
, reshape
size want , take transpose t
(x1,y1),(x2,y2),...
(x1,x2,...),(y1,y2,...)
.
python
Comments
Post a Comment