0_0
is a fully valid Python expression.None
values can be a daunting task: In [1]: data = [ ...: dict(a=1), ...: None, ...: dict(a=-3), ...: dict(a=2), ...: None, ...: ] In [2]: sorted(data, key=lambda x: x['a']) ... TypeError: 'NoneType' object is not subscriptable
In [3]: sorted( ...: (d for d in data if d is not None), ...: key=lambda x: x['a'] ...: ) + [ ...: d for d in data if d is None ...: ] Out[3]: [{'a': -3}, {'a': 1}, {'a': 2}, None, None]
key
: In [4]: sorted(data, key=lambda x: float('inf') if x is None else x['a']) Out[4]: [{'a': -3}, {'a': 1}, {'a': 2}, None, None]
In [5]: sorted(data, key=lambda x: (1, None) if x is None else (0, x['a'])) Out[5]: [{'a': -3}, {'a': 1}, {'a': 2}, None, None]
random.seed()
in each process. But if you use the multiprocessing
module, it will do it for you. import multiprocessing import random import os import sys def test(a): print(random.choice(a), end=' ') a = [1, 2, 3, 4, 5] for _ in range(5): test(a) print() for _ in range(5): p = multiprocessing.Process( target=test, args=(a,) ) p.start() p.join() print() for _ in range(5): pid = os.fork() if pid == 0: test(a) sys.exit() else: os.wait() print()
4 4 4 5 5 1 4 1 3 3 2 2 2 2 2
at_fork
you can do the same with os.fork
. 1 2 2 1 5 4 4 4 5 5 2 4 1 3 1
sum([a, b, c])
equivalent to a + b + c
, although in fact the equivalent would be 0 + a + b + c
. So this expression cannot work with types that do not support addition with 0
: class MyInt: def __init__(self, value): self.value = value def __add__(self, other): return type(self)(self.value + other.value) def __radd__(self, other): return self + other def __repr__(self): class_name = type(self).__name__ return f'{class_name}({self.value})' In : sum([MyInt(1), MyInt(2)]) ... AttributeError: 'int' object has no attribute 'value'
0
: In : sum([MyInt(1), MyInt(2)], MyInt(0)) Out: MyInt(3)
sum
intended for adding float
and int
types, although it can work with any other custom types. However, he refuses to add bytes
, bytearray
and str
, since join
for this purpose: In : sum(['a', 'b'], '') ... TypeError: sum() can't sum strings [use ''.join(seq) instead] In : ints = [x for x in range(10_000)] In : my_ints = [Int(x) for x in ints] In : %timeit sum(ints) 68.3 µs ± 142 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In : %timeit sum(my_ints, Int(0)) 5.81 ms ± 20.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
_ipython_key_completions_
method, _ipython_key_completions_
can customize the completion of indexes in Jupyter Notebook. This way you can control what is displayed on the screen if you press Tab after something like d["x
:Source: https://habr.com/ru/post/447210/
All Articles