Skip to content

Instantly share code, notes, and snippets.

@burukuru
Last active July 12, 2019 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burukuru/0f45cca439ab5fda23f54abf53cc1750 to your computer and use it in GitHub Desktop.
Save burukuru/0f45cca439ab5fda23f54abf53cc1750 to your computer and use it in GitHub Desktop.
Python cheatsheet
# 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