Last active
July 12, 2019 22:38
-
-
Save burukuru/0f45cca439ab5fda23f54abf53cc1750 to your computer and use it in GitHub Desktop.
Python cheatsheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# List comprehension | |
list = [] | |
result = [expr(item) for item in list if item < 5] | |
# Dict comprehension | |
dict = dict() | |
dict = {key: value for key in list} | |
# Range | |
x = range(2, 5) | |
x = [2, 3, 4] | |
# Split/Join | |
list = string.split() | |
" ".join(list) | |
# For loops | |
for n in numbers: | |
print(n) | |
for header, rows in zip(headers, rows): | |
print("{}: {}".format(header, ", ".join(rows))) | |
for num, line in enumerate(lines): | |
print("{0:03d}: {1}".format(num, line)) | |
# Counting | |
l = ["a", "b", "b"] | |
[ [x, l.count(x)] for x in set(l) ] # gives list of list | |
dict((x, l.count(x)) for x in set(l)) # gives dict | |
from collections import Counter | |
Counter(l) -> Counter({'b': 2, 'a': 1}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment