0

I'm creating a function for a game which includes a board and words. I have designed this function and I don't really know if I could use a loop or a list method to run it correctly. This is the function I am creating:

def make_str_from_column(board, column_index):
    """ (list of list of str, int) -> str

    Return the characters from the column of the board with index column_index
    as a single string.

    >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
    'NS'
    """
1
  • 1
    As is, your question is very hard to understand. Where is the actual function implementation? What do you mean by list method? (I'm assuming, you mean a list comprehension) Also, StackOverflow is only for coding questions and we rarely take on things that already work. Questions regarding improvement should be asked on codereview.stackexchange.com. Commented Jan 30, 2017 at 16:57

1 Answer 1

2

You have a couple of options for getting the letters. You could use a simple loop

ret = []
for sublist in board:
    ret.append(sublist[column_index])

You could simplify that into a list comprehension

[sublist[column_index] for sublist in board]

Or you can use zip, which will actually make each column, and then you can choose among them.

list(zip(*board))[column_index]

Personally, I would choose the list comprehension.

Once you have that however, you should use ''.join to combine the list of strings into a single string

return ''.join([sublist[column_index] for sublist in board])
Sign up to request clarification or add additional context in comments.

2 Comments

I think a list comprehension is better too. But in this case I have to use functions that I have created earlier. Under this conditions zip could be used anyway? or use it could be more difficult? PD: I didn't know zip option.
@KennethRivadeneiraGuadamud You can read more about zip here: docs.python.org/3/library/functions.html#zip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.