David Sawyer
David Sawyer

Reputation: 557

Is there a more efficient way to create this 2D list?

I'm taking in a file with several lines of characters, like so:

oeoeoeo
eoeoeoe
oeoeoeo
eoeoeoe
oeoeoeo

I want to put them into a 2D list, like so:

[['o', 'e', 'o', 'e', 'o', 'e', 'o'],
 ['e', 'o', 'e', 'o', 'e', 'o', 'e'],
 ['o', 'e', 'o', 'e', 'o', 'e', 'o'],
 ['e', 'o', 'e', 'o', 'e', 'o', 'e'],
 ['o', 'e', 'o', 'e', 'o', 'e', 'o']]

This is how I'm currently accomplishing this:

map2dArray = []

for line in input_file:
    lineArray = []
    for character in line:
        lineArray.append(character)
    map2dArray.append(lineArray)

Is there a more elegant way to do this in Python?

Upvotes: 0

Views: 59

Answers (1)

nneonneo
nneonneo

Reputation: 179582

Yes, in a single line:

map(list, input_file)

or in Python 3:

list(map(list, input_file))

This generally leaves the newlines in the result, so if you want to get rid of those:

[list(line.strip('\n')) for line in input_file]

Upvotes: 4

Related Questions