• Oct 15, 2022 •CodeCatch
1 like • 2 views
my_list = ["blue", "red", "green"] #1- Using sort or srted directly or with specifc keys my_list.sort() #sorts alphabetically or in an ascending order for numeric data my_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest. # You can use reverse=True to flip the order #2- Using locale and functools import locale from functools import cmp_to_key my_list = sorted(my_list, key=cmp_to_key(locale.strcoll))
• May 31, 2023 •CodeCatch
0 likes • 0 views
class Rectangle: pass class Square(Rectangle): pass rectangle = Rectangle() square = Square() print(isinstance(rectangle, Rectangle)) # True print(isinstance(square, Rectangle)) # True print(isinstance(square, Square)) # True print(isinstance(rectangle, Square)) # False
• Jul 24, 2024 •AustinLeath
0 likes • 3 views
from statistics import median, mean, mode def print_stats(array): print(array) print("median =", median(array)) print("mean =", mean(array)) print("mode =", mode(array)) print() print_stats([1, 2, 3, 3, 4]) print_stats([1, 2, 3, 3])
• Jun 1, 2023 •CodeCatch
0 likes • 1 view
filename = "data.txt" data = "Hello, World!" with open(filename, "a") as file: file.write(data)
• Nov 19, 2022 •CodeCatch
from collections import defaultdict def collect_dictionary(obj): inv_obj = defaultdict(list) for key, value in obj.items(): inv_obj[value].append(key) return dict(inv_obj) ages = { 'Peter': 10, 'Isabel': 10, 'Anna': 9, } collect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] }
• Nov 18, 2022 •AustinLeath
0 likes • 4 views
mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':0} # How to sort a dict by value Python 3> sort = {key:value for key, value in sorted(mydict.items(), key=lambda kv: (kv[1], kv[0]))} print(sort) # How to sort a dict by key Python 3> sort = {key:mydict[key] for key in sorted(mydict.keys())} print(sort)