由 neevop 十二月 8, 2022
List
<list> = <list>[<slice>] # Or: <list>[from_inclusive : to_exclusive : ±step]
<list>.append(<el>) # Or: <list> += [<el>]
<list>.extend(<collection>) # Or: <list> += <collection>
<list>.sort() # Sorts in ascending order.
<list>.reverse() # Reverses the list in-place.
<list> = sorted(<collection>) # Returns a new sorted list.
<iter> = reversed(<list>) # Returns reversed iterator.
sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, el: out * el, <collection>)
list_of_chars = list(<str>)
- For details about sorted(), min() and max() see sortable.
- Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
<list>.insert(<int>, <el>) # Inserts item at index and moves the rest to the right.
<el> = <list>.pop([<int>]) # Removes and returns item at index or from the end.
<int> = <list>.count(<el>) # Returns number of occurrences. Also works on strings.
<int> = <list>.index(<el>) # Returns index of the first occurrence or raises ValueError.
<list>.remove(<el>) # Removes first occurrence of the item or raises ValueError.
<list>.clear() # Removes all items. Also works on dictionary and set.
Dictionary
<view> = <dict>.keys() # Coll. of keys that reflects changes.
<view> = <dict>.values() # Coll. of values that reflects changes.
<view> = <dict>.items() # Coll. of key-value tuples that reflects chgs.
value = <dict>.get(key, default=None) # Returns default if key is missing.
value = <dict>.setdefault(key, default=None) # Returns and writes default if key is missing.
<dict> = collections.defaultdict(<type>) # Returns a dict with default value of type.
<dict> = collections.defaultdict(lambda: 1) # Returns a dict with default value 1.
<dict> = dict(<collection>) # Creates a dict from coll. of key-value pairs.
<dict> = dict(zip(keys, values)) # Creates a dict from two collections.
<dict> = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys.
<dict>.update(<dict>) # Adds items. Replaces ones with matching keys.
value = <dict>.pop(key) # Removes item or raises KeyError.
{k for k, v in <dict>.items() if v == value} # Returns set of keys that point to the value.
{k: v for k, v in <dict>.items() if k in keys} # Returns a dictionary, filtered by keys.
Counter
>>> from collections import Counter
>>> colors = ['blue', 'blue', 'blue', 'red', 'red']
>>> counter = Counter(colors)
>>> counter['yellow'] += 1
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
Set
<set> = set() # `{}` returns a dictionary.
<set>.add(<el>) # Or: <set> |= {<el>}
<set>.update(<collection> [, ...]) # Or: <set> |= <set>
<set> = <set>.union(<coll.>) # Or: <set> | <set>
<set> = <set>.intersection(<coll.>) # Or: <set> & <set>
<set> = <set>.difference(<coll.>) # Or: <set> - <set>
<set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
<bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
<bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set>
<el> = <set>.pop() # Raises KeyError if empty.
<set>.remove(<el>) # Raises KeyError if missing.
<set>.discard(<el>) # Doesn't raise an error.
Frozen Set
- Is immutable and hashable.
- That means it can be used as a key in a dictionary or as an element in a set.
<frozenset> = frozenset(<collection>)
Tuple
Tuple is an immutable and hashable list.
<tuple> = () # Empty tuple.
<tuple> = (<el>,) # Or: <el>,
<tuple> = (<el_1>, <el_2> [, ...]) # Or: <el_1>, <el_2> [, ...]
Named Tuple
Tuple’s subclass with named elements.
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
Range
Immutable and hashable sequence of integers.
<range> = range(stop) # range(to_exclusive)
<range> = range(start, stop) # range(from_inclusive, to_exclusive)
<range> = range(start, stop, ±step) # range(from_inclusive, to_exclusive, ±step_size)
>>> [i for i in range(3)]
[0, 1, 2]
Enumerate
for i, el in enumerate(<collection> [, i_start]):
...
Iterator
<iter> = iter(<collection>) # `iter(<iter>)` returns unmodified iterator.
<iter> = iter(<function>, to_exclusive) # A sequence of return values until 'to_exclusive'.
<el> = next(<iter> [, default]) # Raises StopIteration or returns 'default' on end.
<list> = list(<iter>) # Returns a list of iterator's remaining elements.
Itertools
import itertools as it
<iter> = it.count(start=0, step=1) # Returns updated value endlessly. Accepts floats.
<iter> = it.repeat(<el> [, times]) # Returns element endlessly or 'times' times.
<iter> = it.cycle(<collection>) # Repeats the sequence endlessly.
<iter> = it.chain(<coll>, <coll> [, ...]) # Empties collections in order (figuratively).
<iter> = it.chain.from_iterable(<coll>) # Empties collections inside a collection in order.
<iter> = it.islice(<coll>, to_exclusive) # Only returns first 'to_exclusive' elements.
<iter> = it.islice(<coll>, from_inc, …) # `to_exclusive, +step_size`. Indices can be None.
Generator
- Any function that contains a yield statement returns a generator.
- Generators and iterators are interchangeable.
def count(start, step):
while True:
yield start
start += step
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)