Reputation: 175
Initially I was simply using MatPlotLib to graph the points after I read them like this:
with open("data1.txt") as f:
samples = f.read()
samples = samples.split('\n')
x = [row.split(' ')[0] for row in samples]
y = [row.split(' ')[1] for row in samples]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x,y, 'ro')
However, I now realize I need to store all that information in an array of some kind to be used later. I'm new to python, so I'm wondering either how I could access these points individually if my samples variable already has what I want, or instead create a new array or list to store all my x and y values easily.
EDIT:
This is how my txt file looks:
0.1394 0.8231
1.2149 1.8136
1.3823 0.8263
1.3726 0.8158
1.3694 0.8158
1.3855 0.8123
1.3919 0.8053
1.3694 0.8123
1.3661 0.8123
1.3597 0.7982
1.3565 0.6061
1.3468 0.7126
1.3823 0.7494
Upvotes: 1
Views: 121
Reputation: 180391
If you only have have the x and y just add them in one list comp:
with open("data1.txt") as f:
coords = [line.split() for line in f]
print(coords)
[['0.1394', '0.8231'], ['1.2149', '1.8136'], ['1.3823', '0.8263'], ['1.3726', '0.8158'], ['1.3694', '0.8158'], ['1.3855', '0.8123'], ['1.3919', '0.8053'], ['1.3694', '0.8123'], ['1.3661', '0.8123'], ['1.3597', '0.7982'], ['1.3565', '0.6061'], ['1.3468', '0.7126'], ['1.3823', '0.7494']]
To get floats use coords = [list(map(float,line.split())) for line in f]
[[0.1394, 0.8231], [1.2149, 1.8136], [1.3823, 0.8263], [1.3726, 0.8158], [1.3694, 0.8158], [1.3855, 0.8123], [1.3919, 0.8053], [1.3694, 0.8123], [1.3661, 0.8123], [1.3597, 0.7982], [1.3565, 0.6061], [1.3468, 0.7126], [1.3823, 0.7494]]
You don't need to create two lists and then zip, just do it when your read from the file.
Upvotes: 1
Reputation: 113948
there is a great grouper recipe
samples = samples.split() #split on all whitespace [x1,y1,x2,y2,...]
#you may want to map to int with `map(int,samples)`
coordinates = zip(*[iter(samples)]*2) #group by twos [(x1,y1),(x2,y2),...]
x,y = zip(*coordinates) # x= [x1,x2,...] ; y = [y1,y2,...]
Upvotes: 0
Reputation: 961
This is how you could easily achieve it since you already have the x and y points:
a = [1,2,3]
b = [4,5,6]
print zip(a,b)
output : [(1, 4), (2, 5), (3, 6)]
Upvotes: 0