Definition and usage of dicts, lists, list comprehension etc...
# Makes sure that code is cleaned up after the execution of the body, no matter what the body contains.
class controlled_execution:
def __enter__(self):
# set things up, e.g. open file
return thing # e.g. file itself
def __exit__(self, type, value, traceback):
# tear things down, e.g. close file
with controlled_execution() as thing:
# some code, e.g. write to file
# a = append / r = read / w = write / x = exclusive creation, fails if file exists.
with open('file.txt', 'a') as out:
out.write(var + '/n')
#!/usr/bin/env python
#!/usr/bin/env python3
# Importing from another file/module: Place __init__.py in same folder.
import my_file
from my_file import class_or_function_name
if __name__ == "__main__":
main()
[1 if a>b else 0 for a,b in zip(arr_a, arr_b)] # if a>b else 0 = expression
[1 for a,b in zip(arr_a, arr_b) if a>b] # if a>b = filter
# Initializing from list
keys = ['one', 'two', 'three']
d = {key: 0 for key in keys}
# Iterating
for key in d:
for key in d.keys():
for val in d.values():
for key, value in d.items():
for key, value in d.iteritems(): # Python 2
# d.items() or d.keys() in Python 2 are not dynamic:
>>> d = { "first" : 1, "second" : 2 }
>>> ks = d.keys()
>>> d["third"] = 3
>>> ks
['second', 'first']