>>> a = [1, 2, 3, 4] >>> a.append(a) >>> a [1, 2, 3, 4, [...]] >>> a[4] [1, 2, 3, 4, [...]] >>> a[4][4][4][4][4][4][4][4][4][4] == a True
>>> a = {} >>> b = {} >>> a['b'] = b >>> b['a'] = a >>> print a {'b': {'a': {...}}}
>>> l = [[1, 2, 3], [4, 5], [6], [7, 8, 9]] >>> sum(l, []) [1, 2, 3, 4, 5, 6, 7, 8, 9]
[y for x in data for y in x]
import itertools data = [[1, 2, 3], [4, 5, 6]] list(itertools.chain.from_iterable(data))
from functools import reduce from operator import add data = [[1, 2, 3], [4, 5, 6]] reduce(add, data)
>>> {a:a**2 for a in range(1, 10)} {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
class foo: def normal_call(self): print("normal_call") def call(self): print("first_call") self.call = self.normal_call
>>> y = foo() >>> y.call() first_call >>> y.call() normal_call >>> y.call() normal_call
class GetAttr(object): def __getattribute__(self, name): f = lambda: "Hello {}".format(name) return f
>>> g = GetAttr() >>> g.Mark() 'Hello Mark'
>>> a = set([1,2,3,4]) >>> b = set([3,4,5,6]) >>> a | b # {1, 2, 3, 4, 5, 6} >>> a & b # {3, 4} >>> a < b # False >>> a - b # {1, 2} >>> a ^ b # {1, 2, 5, 6}
{ x for x in range(10)} # set([1, 2, 3]) == {1, 2, 3} set((i*2 for i in range(10))) == {i*2 for i in range(10)}
>>> x = 5 >>> 1 < x < 10 True >>> 10 < x < 20 False >>> x < 10 < x*10 < 100 True >>> 10 > x <= 9 True >>> 5 == x > 4 True
>>> NewType = type("NewType", (object,), {"x": "hello"}) >>> n = NewType() >>> nx 'hello'
>>> class NewType(object): >>> x = "hello" >>> n = NewType() >>> nx "hello"
sum[value] = sum.get(value, 0) + 1
>>> d = {} >>> a, b = 4, 5 >>> d[a] = list() >>> d {4: []} >>> d[a].append(b) >>> d {4: [5]}
x = 1 if (y == 10) else 2 # X 1, , Y 10. - X 2 x = 3 if (y == 1) else 2 if (y == -1) else 1 # . elif
>>> first,second,*rest = (1,2,3,4,5,6,7,8) >>> first # 1 >>> second # 2 >>> rest # [3, 4, 5, 6, 7, 8]
>>> first,*rest,last = (1,2,3,4,5,6,7,8) >>> first 1 >>> rest [2, 3, 4, 5, 6, 7] >>> last 8
>>> l = ["spam", "ham", "eggs"] >>> list(enumerate(l)) >>> [(0, "spam"), (1, "ham"), (2, "eggs")] >>> list(enumerate(l, 1)) # >>> [(1, "spam"), (2, "ham"), (3, "eggs")]
try: function() except Error: # try Error else: # try except finally: #
>>> x = [1, 2, 3] >>> y = x >>> y[2] = 5 >>> y [1, 2, 5] >>> x [1, 2, 5]
>>> x = [1,2,3] >>> y = x[:] >>> y.pop() 3 >>> y [1, 2] >>> x [1, 2, 3]
import copy my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]} my_copy_dict = copy.deepcopy(my_dict)
>>> l = ['a', 'b', 'c', 'd', 'e'] >>> for i, value_list in enumerate(l, 1): # 1 - >>> print(i, value_list) ... 1 a 2 b 3 c 4 d 5 e
>>> def foo(x=[]): ... x.append(1) ... print x ... >>> foo() [1] >>> foo() [1, 1] # [1] >>> foo() [1, 1, 1]
>>> def foo(x=None): ... if x is None: ... x = [] ... x.append(1) ... print x >>> foo() [1] >>> foo() [1]
class MyDict(dict): # def __missing__(self, key): return key ... >>> m = MyDict(a=1, b=2, c=3) # >>> m {'a': 1, 'c': 3, 'b': 2} >>> m['a'] # 1 1 >>> m['z'] # 'z'
>>> def print_args(function): >>> def wrapper(*args, **kwargs): >>> print ' : ', args, kwargs >>> return function(*args, **kwargs) >>> return wrapper >>> @print_args >>> def write(text): >>> print text >>> write('foo') Arguments: ('foo',) {} foo
@f1(arg) @f2 def func(): pass
def func(): pass func = f1(arg)(f2(func))
>>> a = 10 >>> b = 5 >>> a, b (10, 5) >>> a, b = b, a >>> a, b (5, 10)
>>> def jim(phrase): ... return 'Jim says, "%s".' % phrase >>> def say_something(person, phrase): ... print person(phrase) >>> say_something(jim, 'hey guys') # 'Jim says, "hey guys".'
# g(), . # "100" ( (7+3)×(7+3)). def f(x): return x + 3 def g(function, x): return function(x) * function(x) print g(f, 7)
>>> round(1234.5678, -2) 1200.0 >>> round(1234.5678, 2) 1234.57
import this
from __future__ import braces
a = [1,2,3,4,5] >>> a[::2] # [1,3,5]
>>> a[::-1] # [5,4,3,2,1]
import webbrowser webbrowser.open_new_tab('http://habrahabr.ru/') # True
a = [(1,2), (3,4), (5,6)] zip(*a) # [(1, 3, 5), (2, 4, 6)]
>>> t1 = (1, 2, 3) >>> t2 = (4, 5, 6) >>> dict (zip(t1,t2)) {1: 4, 2: 5, 3: 6}
>>> a = range(10) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[:5] = [42] # 5 "42" >>> a [42, 5, 6, 7, 8, 9] >>> a[:1] = range(5) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> del a[::2] # >>> a [1, 3, 5, 7, 9] >>> a[::2] = a[::-2] # reserved >>> a [9, 3, 5, 7, 1]
>>> m = {} >>> m.setdefault('foo', []).append(1) >>> m {'foo': [1]} >>> m.setdefault('foo', []).append(2) >>> m {'foo': [1, 2]}
import antigravity
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number'
import __hello__
>>> # >>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} >>> # >>> OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) >>> # >>> OrderedDict(sorted(d.items(), key=lambda t: t[1])) OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) >>> # >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0]))) OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
class Worm: def creep(self): print("i am creeping") class Butterfly: def fly(self): print("i am flying") creature = Worm() creature.creep() creature.__class__ = Butterfly creature.fly()
from collections import Counter Counter('habrahabr') # Counter({'a': 3, 'h': 2, 'r': 2, 'b': 2})
assert x>y
assert <test>, <data>
if __debug__: if not <test>: raise AssertationError, <data>
Source: https://habr.com/ru/post/207988/
All Articles