Skip to content

Instantly share code, notes, and snippets.

@vchan14
Last active June 14, 2020 18:17
Show Gist options
  • Save vchan14/11d920376879da648e16cb5c2e6c396e to your computer and use it in GitHub Desktop.
Save vchan14/11d920376879da648e16cb5c2e6c396e to your computer and use it in GitHub Desktop.
Five Most Common Python Shortcuts
sentence = "i like apple"
# Create a dictionary counting character frequency of ``sentence``
# With using default dicionary
from collections import defaultdict
frequencies = defaultdict(int)
for char in sentence:
frequencies[char] += 1
# Without using defualt dictionary
frequencies = {}
for char in sentence:
if char in frequencies:
frequencies[char] += 1
else:
frequencies[char] = 1
import collections
people = ["James", "Messi", "James", "Ronaldo"]
peopleAppearAt = collections.defaultdict(list)
for i, name in enumerate(people):
peopleAppearAt[name].append(i)
# Result
peopleAppearAt :
{
"James" : [0, 2],
"Messi" : [1],
"Ronaldo" : [3]
}
# Create a 4 x 2 matrix
col = 4
row = 2
matrix = [[0]*col for _ in range(row)]
arr = [5, 1, 3]
# Sort not in place (return a new array)
new_sorted_array = sorted(arr)
# Sort in place (return None)
arr.sort()
animal_age = [[4,"cat"], [1, "dog"], [2, "cat"]]
# Sort the list by first index or age
# animal_age : [[1, 'dog'], [2, 'cat'], [4, 'cat']]
animal_age.sort(key = lambda x : x[0])
# Sort the list by second index or name of animals
# animal_age : [[2, 'cat'], [4, 'cat'], [1, 'dog']]
animal_age.sort(key = lambda x : x[1])
# Sort the list by both attributes by comparing the name first
# if tie, compare the age from old to young(descendingly)
# animal_age = [[4, 'cat'], [2, 'cat'], [1, 'dog']]
animal_age.sort(key = lambda x: (x[1], -x[0]))
# Format of Python Ternary
"""
value = value_when_true if condition else value_when_false
"""
# Example
x = 5
equal_five = True if x == 5 else False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment