Created
February 22, 2018 14:07
-
-
Save brodo/dbf3d2f3734d556e2a0240157a33ca5f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Dictionary-Comprehensions | |
characters = [ | |
"0,Regulus Arcturus Black", | |
"1,Sirius Black", | |
"2,Lavender Brown", | |
"3,Cho Chang", | |
"4,Vincent Crabbe Sr.", | |
"5,Vincent Crabbe", | |
"6,Bartemius Crouch Sr.", | |
"7,Bartemius Crouch Jr.", | |
"8,Fleur Delacour", | |
"9,Cedric Diggory", | |
"10,Alberforth Dumbledore", | |
"11,Albus Dumbledore", | |
"12,Dudley Dursley", | |
"13,Petunia Dursley", | |
"14,Vernon Dursley" | |
] | |
characters_list = [c.split(",") for c in characters] | |
characters_dict = { k : v for k, v in characters_list} | |
print(characters_dict) | |
# Dedent | |
from textwrap import dedent | |
my_poem = """ | |
I like to think (and | |
the sooner the better!) | |
of a cybernetic meadow | |
where mammals and computers | |
live together in mutually | |
programming harmony | |
like pure water | |
touching clear sky.""" | |
print(dedent(my_poem)) | |
# Generators and yield | |
def generate_numners(): | |
x=0 | |
while True: | |
x += 1 | |
yield x | |
generator = generate_numners() | |
print(generator) | |
even = (x for x in generator if x % 2 == 0) | |
# even = filter(lambda x: x % 2 == 0, generator) print(even) | |
for num in even[:20]: | |
print(num) | |
# Named Tuples | |
from collections import namedtuple | |
Point = namedtuple('Point', ['x', 'y']) | |
p = Point(11, y=22) # instantiate with positional or keyword arguments | |
print(p[0] + p[1]) # indexable like the plain tuple (11, 22) | |
x, y = p # unpack like a regular tuple | |
p.x + p.y | |
# Decoratos | |
def escape_unicode(fun): | |
def wrap(*args, **kwargs): | |
x = fun(*args, **kwargs) | |
return ascii(x) | |
return wrap | |
@escape_unicode | |
def swedisch_island(name): | |
return f"{name} ö" | |
print(swedisch_island(name = "Hasi")) | |
# Type Annotations | |
a : int = 5 | |
b : str = "Hallo Welt" | |
c : float = .5 | |
def add(a : int, b:int) -> int: | |
return a + b | |
##> pip3 install mypy | |
##> mypy bla.py | |
from typing import Callable, List | |
def my_list(): | |
return [1,2,3,4] | |
def add_ints(fun : Callable[[], List[int]]): | |
sum = 0 | |
for x in fun(): | |
sum += x | |
return sum | |
print(add_ints(my_list)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment