2D List comprehension & replace

Dang Griffith noemail at noemail4u.com
Fri Mar 12 09:50:33 EST 2004


On Thu, 11 Mar 2004 18:13:28 -0600, "Larry Bates"
<lbates at swamisoft.com> wrote:

>I've gone brain-dead trying to get this to work
>using list comprehensions.  I have a list of lists
>like the following:
>
>l=[[92.6, 0, 93.5],
>   [94.7, 95.6, 95.7],
>   [91.2, 92.1, 93.0]]
>
>what I want is a new list
>with the zero (0) replaced with None.
>
>I thought I would use the fact that the command:
>
>0 or None
>
>seems to return None.
>
>This procedural code does the trick, but I just
>know it can be done with a single list comprehension.
>
>tol=[]
>for a in l:
>    til=[]
>    for v in a:
>        if a != 0: til.append(v)
>        else:      til.append(None)
>
>    tol.append(til)
>
>l=tol
>
>Thanks in advance.
>
>Larry Bates
>

def NonifyNestedList(rows):
    return [[item or None for item in cols] for cols in rows]

    --dang



More information about the Python-list mailing list