Skip to content

Instantly share code, notes, and snippets.

@usametov
Created June 27, 2020 18:26
Show Gist options
  • Save usametov/f834c57e9d458897e1e458c55ba32e5d to your computer and use it in GitHub Desktop.
Save usametov/f834c57e9d458897e1e458c55ba32e5d to your computer and use it in GitHub Desktop.
# https://stackoverflow.com/questions/1143671/how-to-sort-objects-by-multiple-keys-in-python/29849371
people = [
{ 'name': 'John', "age": 64 },
{ 'name': 'Janet', "age": 34 },
{ 'name': 'Ed', "age": 24 },
{ 'name': 'Sara', "age": 64 },
{ 'name': 'John', "age": 32 },
{ 'name': 'Jane', "age": 34 },
{ 'name': 'John', "age": 99 },
]
people.sort(key=operator.itemgetter('age'))
people.sort(key=operator.itemgetter('name'))
# list comprehensions
mylist = [i for i in range(10)]
print(mylist)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares = [x**2 for x in range(10)]
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
def some_function(a):
return (a + 5) / 2
my_formula = [some_function(i) for i in range(10)]
print(my_formula)
# [2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]
filtered = [i for i in range(20) if i%2==0]
print(filtered)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# memory
import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist))
# 48
import sys
myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))
# 87632
# data classes
# https://realpython.com/python-data-classes/
# https://www.attrs.org/en/stable/examples.html
from dataclasses import dataclass
@dataclass
class Card:
rank: str
suit: str
card = Card("Q", "hearts")
print(card == card)
# True
print(card.rank)
# 'Q'
print(card)
Card(rank='Q', suit='hearts')
# attrs package
@attrs
class Person(object):
name = attrib(default='John')
surname = attrib(default='Doe')
age = attrib(init=False)
p = Person()
print(p)
p = Person('Bill', 'Gates')
p.age = 60
print(p)
# Output:
# Person(name='John', surname='Doe', age=NOTHING)
# Person(name='Bill', surname='Gates', age=60)
# dictionaries
dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = { **dict1, **dict2 }
print (merged)
# {'a': 1, 'b': 3, 'c': 4}
#In Python 3.9, merging dictionaries becomes even cleaner. The above merge in Python 3.9 can be rewritten as:
merged = dict1 | dict2
#Most Frequently Occurring Value
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
# 4
# Return Multiple Values
def get_user(id):
# fetch user from database
# ....
return name, birthdate
name, birthdate = get_user(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment