About me

About

2011-09-26

Alguns "python one liners" interessantes.

Algumas construções one liners de python.

  1. remover duplicados numa lista

    >>> list = [1,2,3,3,4,4,5]
    >>> list = filter(lambda x,map={}: not (map.has_key(x) or map.setdefault(x, 0)), list)
    >>> list
    [1, 2, 3, 4, 5]
  2. simular o operador de C “condition ? expr_true : expr_false”

    1. se expr_true e expr_false são expressões avaliadas como boolean, basta a construção: condition or expr_true and expr_false

      >>> x=0
      >>> print x==1 and "1" or x==2 and "2" or x==3 and "3" or "nada"
      nada
    2. genericamente: (expr_false,expr_true)[condition]

      >>> x="foo"
      >>> print (x,None)[x=="NULL"]
      foo
      >>> x="NULL"
      >>> print (x,None)[x=="NULL"]
      None

Sem comentários:

Enviar um comentário