4.2 KiB
4.2 KiB
virtualenv
virtualenv venv
source venv/bin/activate
deactivate
Dictionaries
d.items()returns an iterable with key-value pairs as tuplesd.keys()returns an iterable with all keysd.values()returns an iterable with all valuesdict(sorted(d.items()))returns a dict sorted by keysdict(sorted(d.items(), key=lambda x: x[1]))returns a dict sorted by valuesd.get(key, default=None)returns the value for a keyd.pop(key, default=None)removes the key and returns the value for keyd.popitem()removes the last item added and returns it as(key, value)(LIFO)
Flow Control
break: Terminate the current loop.continue: Skip the current iteration of a loop and move to the next iteration.pass: Do nothing.
Iterables
i.all()returns True if all items are Truei.any()returns True if any item is Truei.min()returns smallest itemi.max()returns largest itemi.sum()returns sum of all itemsreversed(i)returns the reverse
sorted(list)
sorted(list, reverse=True)
sorted(string_list, key=str.lower) # Sort by lower case
sorted(string_list, key=int) # Sort by casted integer
for i, el in enumerate(list):
print(i, el) ## i = index, el = element
Merge 2+ lists into one list containing tuples of mapped items:
list(zip(i1, i2, ...)) # length = shorted list
from itertools import zip_longest
zip_longest(i1, i2, fillvalue="?") # length = longest list, filled with "?"
List Comprehension
[expression for item in iterable if condition]
[expression if condition else other_expression for item in iterable]
Filter a list with [x for x in iterable if condition].
List Misc
list.extend(iterable)extends the list by appending all itemslist.insert(i, x)insertsxat positionilist.remove(x)removes the first occurrence ofxlist.count(x)counts the number ofxlist.pop(i)removes and returns item at positioni
Queue and Stack
queue = []
queue.append(item) # Add to end
queue.pop(0) # Remove and return first
stack = []
stack.append(item) # Add to end
stack.pop() # Remove and return last
Sets
s = set()
s.add(item)
s.remove(item)
if item in s: ...
Substrings
substring = s[start:end:step]
Optional args:
- start: Starting index (inclusive). Defaults to 0.
- end: Stopping index (exclusive). Defaults to the end.
- step: Defaults to 1.
s[::-1] reverses a string.
String Misc
All string functions return values, no in-place modifications.
s.strip()removes any leading and trailing whitespaces (alsolstrip()andrstrip())''.join(sorted(s))sorts the characters in a strings.zfill(n)adds 0 to the beginning until the string isnchar long.s.isdigit()returns True if all chars in the string are digitss.isalpha()returns True if all chars in the string are in the alphabets.startswith(value)returns True if the string starts withvalue(can be a tuple for multiple checks)s.upper()/s.lower()for case conversions.replace(old, new, count)returns string with the firstcountoccurences ofoldreplaced bynewlist(s)converts a string into a list of charss.split(separator, maxsplit)splits a string (separatordefaults to any whitespace, optionally stop splitting aftermaxsplitsplits)s.rsplit()splits from the rights.find(value)returns the index of the first occurrence ofvalue, otherwise -1
Class
class ClassName:
"""Class description"""
def __init__(self, arg1, arg2=None):
"""
Initializes an object
Args:
[...]
"""
self.arg1 = arg1
self.arg2 = arg2
def __str__(self):
return (f"{self.arg1=}, {self.arg2=}")
def function_a(self, new_arg2):
self.new_arg2 = new_arg2
obj1 = ClassName("asdf")
print(obj1)
Tests
import pytest
def test_simple():
assert function_a() == "Hello"
@pytest.mark.parametrize("input, expected", [
(input1, "Hello"), (input2, "Hi")
])
def test_parameter(input, expected):
assert function_b(input) == expected