Easy question

Alex Martelli aleaxit at yahoo.com
Wed Apr 11 17:27:20 EDT 2001


"Duncan Smith" <buzzard at urubu.freeserve.co.uk> wrote in message
news:9b2fdh$3ph$1 at news7.svr.pol.co.uk...
> I need to read some data from a file.  Each (tab delimited) row
corresponds
> to an array index eg.
>
> 0    0    0    0    0    0
> 0    1    0    0    0    0
> 0    0    1    0    0    0
> ...
>
> And I need something like,
>
> [[0,0,0,0,0,0], [0,1,0,0,0,0], [0,0,1,0,0,0], ...]
>
> What's the best way of doing this?  Cheers in advance.

It takes some good taste to choose the right balance between
concision and clarity here.  One possibility:

def forDuncan(fileobj):
    result = []
    for line in fileobj.readlines():
        result.append(map(int, line.split()))
    return result

One could be more compact:

def forDuncan1(fileobj):
    return [ map(int, line.split())
        for line in fileobj.readlines() ]

or less compact:

def forDuncan2(fileobj):
    result = []
    for line in fileobj.readlines():
        subresult = []
        for field in line.split():
            subresult.append(int(field))
        result.append(subresult)
    return result


Personally, in this specific case I happen to prefer the
most compact version, forDuncan1 -- it seems to me
that it captures the key ideas most clearly through its
concision, while the other versions add no clarity, just
repetitious boilerplate, through their explicit loops.


Alex






More information about the Python-list mailing list