#----------------------------------------------------------------------- halve_evens_only = lambda nums: map(lambda i: i/2, filter(lambda i: not i%2, nums)) #----------------------------------------------------------------------- def halve_evens_only(nums): return [i/2 for i in nums if not i % 2]
a, b = b, a
a = [1,2,3,4,5] >>> a[::2] # iterate over the whole list in 2-increments [1,3,5]
>>> a[::-1] [5,4,3,2,1]
>>> x[::-1] [5, 4, 3, 2, 1] >>> x[::-2] [5, 3, 1]
def function(x, l=[]): # Don't do this def function(x, l=None): # Way better if l is None: l = []
d = {1: "1", 2: "2", 3: "3"} for key, val in d.items() # builds complete list when called. for key, val in d.iteritems() # calls values only when requested.
if type(s) == type(""): ... if type(seq) == list or \ type(seq) == tuple: ...
if isinstance(s, basestring): ... if isinstance(seq, (list, tuple)): ...
>>> a=u'aaaa' >>> print isinstance(a, basestring) True >>> print isinstance(a, str) False
object | | basestring / \ / \ str unicode
freqs = {} for c in "abracadabra": try: freqs[c] += 1 except: freqs[c] = 1
freqs = {} for c in "abracadabra": freqs[c] = freqs.get(c, 0) + 1
from collections import defaultdict freqs = defaultdict(int) for c in "abracadabra": freqs[c] += 1
namedtuple() # factory function for creating tuple subclasses with named fields deque # list-like container with fast appends and pops on either end Counter # dict subclass for counting hashable objects OrderedDict # dict subclass that remembers the order entries were added defaultdict # dict subclass that calls a factory function to supply missing values
>>> from collections import Counter >>> c = Counter("abracadabra") >>> c['a'] 5
__eq__(self, other) # Defines behavior for the equality operator, ==. __ne__(self, other) # Defines behavior for the inequality operator, !=. __lt__(self, other) # Defines behavior for the less-than operator, <. __gt__(self, other) # Defines behavior for the greater-than operator, >. __le__(self, other) # Defines behavior for the less-than-or-equal-to operator, <=. __ge__(self, other) # Defines behavior for the greater-than-or-equal-to operator, >=.
x = 3 if (y == 1) else 2
x = 3 if (y == 1) else 2 if (y == -1) else 1
(func1 if y == 1 else func2)(arg1, arg2)
x = (class1 if y == 1 else class2)(arg1, arg2)
>>> from numpy import arange >>> a = arange(16).reshape(2,2,2,2)
>>> a[..., 0].flatten() array([ 0, 2, 4, 6, 8, 10, 12, 14])
>>> a[:,:,:,0].flatten() array([ 0, 2, 4, 6, 8, 10, 12, 14])
class MyClass(object): def __init__(self, a, b, c, d): self.a, self.b, self.c, self.d = a, b, c, d def __getitem__(self, item): return getattr(self, item) x = MyClass(10, 12, 22, 14)
def __getitem__(self, item): if item is Ellipsis: return [self.a, self.b, self.c, self.d] else: return getattr(self, item)
>>> x = MyClass(11, 34, 23, 12) >>> x[...] [11, 34, 23, 12]
Source: https://habr.com/ru/post/144614/
All Articles