Reputation: 13
I want to convert series of numbers in to arrays in Python without using any libraries. ( 0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8) (1,3 3,4 5,9 7,5 10,2 11,4 20,10 ) (0,0 6,6 12,3 19,6 (green)) for example these three series. Is it possible to do it without libraries like numpy? I tried to use numpy but and reached the solution like this for the first series.
array([[ 0, 2],
[ 3, 0],
[ 4, 5],
[ 7, 8],
[ 8, 6],
[ 9, 5],
[13, 6],
[15, 9],
[17, 10],
[21, 8]])
but the professor did not accept that.
Upvotes: 1
Views: 543
Reputation: 8608
If
a = "1,2 2,3 3,4 ..."
then
result = [map(int, v.split(",")) for v in a.split()]
Will give you
print result
[[1, 2], [2, 3], [3, 4], ... ]
Upvotes: 1
Reputation: 16
If series of numbers are string line then you could try next code:
a = "0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8"
lines = a.split(' ')
arr = [[int(i) for i in x.split(',')] for x in lines]
print arr
output
[[0, 2], [3, 0], [4, 5], [7, 8], [8, 6], [9, 5], [13, 6], [15, 9], [17, 10], [21, 8]]
EDIT (avoid O(n^2)):
One way passing:
a = "0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8"
position = 0
previous_position = 0
final_array = []
temp_array = []
for character in a:
if character == ',':
temp_array = []
temp_array.append(int(a[previous_position:position]))
previous_position = position
elif character == ' ':
temp_array.append(int(a[previous_position+1:position]))
previous_position = position+1
final_array.append(temp_array)
elif position == len(a) - 1:
temp_array.append(int(a[previous_position+1:]))
final_array.append(temp_array)
position += 1
print final_array
Upvotes: 0