user5428826
user5428826

Reputation:

Python- appending coordinate-like string into list

I am attempting to append a coordinate-like value into a list. the following is my code so far, but it returns ["(0,1),(1,1),(1,2)"] when I need it to return [(0,1),(1,1),(1,2)].

def read_coords(s):
    coords_s = []
    row = 0
    split_coords = s.split('\n')
    for i in split_coords:
        i = list(i)
        for z in range(len(i)):
            indiv_coord = []
            if i[z] == 'O':
                coords_s.append('('+str(row)+','+str(z)+')')
                row += 1            
    return coords_s

The test cases I am using are:

read_coords("O..\n.OO\n") which should return --> [(0,0), (1,1), (1,2)] o read_coords("\n\nO..\n.OO\n\n") → `[(0,0), (1,1), (1,2)]

ignores blank lines.

read_coords(".....\n.....\n")[]

Upvotes: 2

Views: 252

Answers (1)

idjaw
idjaw

Reputation: 26578

You aren't creating the data structure you think you are.

This line you have here:

coords_s.append('('+str(row)+','+str(z)+')')

What you are doing there is actually appending a string to your list as "(row, z)".

The structure you are referring to is called a tuple.

You should be changing your code to actually append the tuple to your list, and the type-casting to str is most likely unnecessary either. So, you can simply do this:

coords_s.append((row, z))

Upvotes: 3

Related Questions