[Python] Complex list comprehension - one liner

Discussão em 'Python' iniciado por Stack, Fevereiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I attempted to create a one-liner to print out this ("the non-perfect list of safe characters for filenames, in most operating systems"):

    $ python ./z.py
    +,-.
    0123456789
    @ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_
    abcdefghijklmnopqrstuvwxyz{}~


    ...but have not found a way to do it; so had to create a short script instead

    My final one-liner attempt:

    $ python -c "lst= [ [0x2b,0x2e+1],[0x30,0x39+1],[0x40,0x5f+1],[0x61,0x7f+1] ];print( [ chr(c) if (c & 0xdf)!=0x5c else '' for c in [ range(a,b) for a,b in [ li for li in lst ] ] ] )"
    Traceback (most recent call last):
    File "<string>", line 1, in <module>
    TypeError: unsupported operand type(s) for &: 'range' and 'int'


    the above output created by z.py containing:

    #!/bin/env python

    # copy of the one-liner
    # python -c "lst= [ [0x2b,0x2e+1],[0x30,0x39+1],[0x40,0x5f+1],[0x61,0x7f+1] ];print( [ chr(c) if (c & 0xdf)!=0x5c else '' for c in [ range(a,b) for a,b in [ li for li in lst ] ] ] )"

    # attempt to break down of the above
    # python -c "lst= [ [0x2b,0x2e+1],[0x30,0x39+1],[0x40,0x5f+1],[0x61,0x7f+1] ];print(
    # [ chr(c) if (c & 0xdf)!=0x5c else '' for c in
    # [ range(a,b) for a,b in
    # [ li for li in lst ]
    # ]
    # ]
    # )"

    # working code to create the output
    lst= [ [0x2b,0x2e+1],[0x30,0x39+1],[0x40,0x5f+1],[0x61,0x7f+1] ]

    for li in lst:
    a,b=li
    for c in range(a,b):
    z=(c & 0xdf)
    if z != 0x5c:
    print(chr(c), end='')
    print()


    Where is the problem with the one liner, can you pinpoint how to do it?

    Continue reading...

Compartilhe esta Página