Skip to content

Instantly share code, notes, and snippets.

@lorne-luo
Last active January 16, 2020 04:07
Show Gist options
  • Save lorne-luo/fa3caf70b86a5311c83cac207667839c to your computer and use it in GitHub Desktop.
Save lorne-luo/fa3caf70b86a5311c83cac207667839c to your computer and use it in GitHub Desktop.
Python snippet
# Occurrence Counter in List
num_lst = [1, 1, 2, 3, 4, 5, 3, 2, 3, 4, 2, 1, 2, 3]
cnt = Counter(num_lst)
print(dict(cnt))
# first 2 most occurrence
print(dict(cnt.most_common(2)))
str_lst = ['blue', 'red', 'green', 'blue', 'red', 'red', 'green']
print(dict(Counter(str_lst)))
# upper case set
import string
string.ascii_uppercase
# Loop Over Multiple Lists at the Same Time
colors = ["red", "green", "yellow", "blue"]
codes = [1, 2, 3, 4]
for color, code in zip(colors, codes):
print(f"{code}, {color}")
from itertools import zip_longest
colors = ["red", "green", "yellow", "blue"]
codes = [1, 2, 3, 4, 5, 6]
for color, code in zip_longest(colors, codes):
print(f"{code}, {color}")
# accumulate()
import itertools
import operator
data = [1, 2, 3, 4, 5]
result = list(itertools.accumulate(data, operator.add))
print(result)
# Reverse a String or List
a = "humanbeing"
print("Reversed : {a[::-1]}")
b = [1, 2, 3, 4, 5]
print("Reversed : {b[::-1]}")
# Flatten Nested List
import itertools
flatten = lambda x: list(itertools.chain.from_iterable(x))
s = [['Every', 'piece of'], ['software written today is', 'likely'], ['going to'], ['infringe on', "someone else’s", 'patent.']]
print(' '.join(flatten(s)))
# Calling Different Functions With the Same Arguments Based on Conditions
def product(a, b):
return a*b
def add(a, b):
return a+b
print((product if True else add)(5, 6))
# Sort Dictionary
from operator import itemgetter
d = {'a': 10, 'b': 20, 'c': 5, 'd': 8, 'e': 5}
# sort by value
print(sorted(d.items(), key=lambda x: x[1]))
# sort by value
print(sorted(d.items(), key=itemgetter(1)))
# sort by key
print(sorted(d.items(), key=itemgetter(0)))
# sort by value and return keys
print(sorted(d, key=d.get))
# Remove Duplicates From List
lst = [7, 3, 3, 5, 6, 5]
# removes duplicates but does not preserves the list order
no_dups = list(set(lst))
print(no_dups)
# removes duplicates and preserves the list order
from collections import OrderedDict
no_dups = list(OrderedDict.fromkeys(lst).keys())
print(no_dups)
# Easy Printing
row = [100, "android", "ios", "blackberry"]
print(*row, sep=', ')
# Index of Min/Max Element
def min_index(lst):
return min(range(len(lst)), key=lst.__getitem__)
def max_index(lst):
return max(range(len(lst)), key=lst.__getitem__)
lst = [20, 40, 70, 10]
print("min index : {}".format(min_index(lst)))
print("max index : {}".format(max_index(lst)))
# Checking Anagram
from collections import Counter
print(Counter('elbow') == Counter('below'))
print(Counter('study') == Counter('night'))
# Merge Dictionaries
d1 = {'a': 1}
d2 = {'b': 2}
print(dict(d1.items() | d2.items()))
print({**d1, **d2})
print(d1.update(d2))
# for loop to dict
words = ['goodbye', 'cruel', 'world']
data = {word: len(word) for word in words}
#{"goodbye": 7, "cruel": 5, "world": 5}
# create generator via for loop
text = open("requirements.txt", "r")
lines = [line for line in text if line.startswith("py")] # list
lines = (line for line in text if line.startswith("py")) # generator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment