Resposta que eu dei à pergunta: Quais são alguns dos recursos ocultos do Python? no Quora.
1. Atribuição múltipla (com tuple unpacking)
a, b, c = 1, 2, 3
2. Com isso dá para trocar o valor de variáveis
a, b = b, a
3. Encadeamento de comparadores
x = 3 print(1 < x < 5) # True
4. Generators
def fib(max): n1, n2 = 0, 1 for i in range(max): yield n1 n1, n2 = n2, n1 + n2 f = fib(20) for i in f: print(i)
5. If em uma linha
aliquota = 0.05 if valor < 1000 else 0.07
6. List comprehension
# Quadrados dos números de 0 a 99 [i ** 2 for i in range(100)] # Quadrados dos números de 0 a 99, apenas # se o resultado não contém o dígito "4" [i ** 2 for i in range(100) if not '4' in str(i**2)]
7. Invertendo uma string
a = a[::-1]
8. enumerate
for i, l in enumerate('palavra'): print (i, l, end=' / ') # 0 p / 1 a / 2 l / 3 a / 4 v / 5 r / 6 a /
9. Unpacking estendido (só Python 3)
a, *b, c = "unpacking" print(a, b, c) # u ['n', 'p', 'a', 'c', 'k', 'i', 'n'] g
10. Dict comprehension
d = {i: i**2 for i in range(10)} print(d) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
11. String formatting
dados={'nome': 'Joaquim', 'email': 'jsilva@fbi.gov'} print('%(nome)s <%(email)s>' % dados) # Joaquim <jsilva@fbi.gov> print('{nome} <{email}>'.format(**dados)) # Joaquim <jsilva@fbi.gov>
12. zip
list(zip([1, 2, 3], [4, 5, 6])) [(1, 4), (2, 5), (3, 6)]
Módulos Úteis
1. collections
import collections print(collections.Counter('banana')) # Counter({'a': 3, 'n': 2, 'b': 1}) d = collections.defaultdict(lambda:'...') d['nome'] = 'Teste' print(d['nome']) # Teste print(d['idade']) # ...
2. pprint
from pprint import pprint pprint(['a' * i for i in range(20)]) # ['', # 'a', # 'aa', # 'aaa', # 'aaaa', # 'aaaaa', # 'aaaaaa', # 'aaaaaaa', # 'aaaaaaaa', # 'aaaaaaaaa', # 'aaaaaaaaaa', # 'aaaaaaaaaaa', # 'aaaaaaaaaaaa', # 'aaaaaaaaaaaaa', # 'aaaaaaaaaaaaaa', # 'aaaaaaaaaaaaaaa', # 'aaaaaaaaaaaaaaaa', # 'aaaaaaaaaaaaaaaaa', # 'aaaaaaaaaaaaaaaaaa', # 'aaaaaaaaaaaaaaaaaaa']
3. itertools
import itertools for i in itertools.permutations("123"): print("".join(i), end=", ") # 123, 132, 213, 231, 312, 321, for i in itertools.product("01", repeat=3): print("".join(i), end=", ") # 000, 001, 010, 011, 100, 101, 110, 111,
4. SimpleHTTPServer
➜ ~ python -m SimpleHTTPServer Serving HTTP on 0.0.0.0 port 8000 ...
5. webbrowser
import webbrowser webbrowser.open('https://campus.visie.com.br/')
6. atexit
➜ ~ python3 -q >>> def teste(): ... print('Bye!') ... >>> import atexit >>> atexit.register(teste) <function teste at 0x10973a620> >>> ^D Bye! ➜ ~ _
7. base64
import base64 print(base64.b64encode(b'Teste')) # b'VGVzdGU='
8. gzip
import gzip print(gzip.open('teste.txt.gz').read())
Easter Eggs
Tente aí:
>> import this >> import hello >> import antigravity >> from __future__ import braces