Coding, Python

Python fun #3 : Directly Input from a text file to a processed 2-D list (in 1 statement)

Suppose you have input file like this(triangle.txt) to use as input …

with open('triangle.txt') as f:
    D = [[int(w) for w in line.split()] for line in f]

This will create a nice table-like 2-D list, i.e. a list of lists. The member list(s) can be of variable size. You can modify the int(w) for w in line.split() part to incorporate your processing.


For solving this problem, I was using this below code segment; so, i raised a question on StackOverflow requesting a smart one-liner. That’s how, I got the above 1-liner Python code.

My dumb code(yet, right) was:

for i in range(100):

// processing
for i in range(100):
for i in range(100):
    for j in range(len(D[i])):
        D[i][j]= int(D[i][j])

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s