Last active
March 10, 2019 12:56
-
-
Save qmmr/0fc3cce1027198d0a8c1ce4190edaacb to your computer and use it in GitHub Desktop.
Tips & tricks in Python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A collection of useful tips when working with Python 3 | |
""" | |
import json | |
# from collections import Hashable | |
from random import choice, randrange | |
# Check if sth is "hashable" cause Sets only store unique and hashable items | |
# Whereas Lists can store anything | |
# print("Is empty object {} hashable? -> {0:b} ") | |
# print(isinstance({}, Hashable)) | |
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, | |
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] | |
# Iterate over list with index and value | |
for idx, val in enumerate(primes): | |
print("At index {idx} is {prime}".format(idx=idx, prime=val)) | |
print("\n\n---\n\n") | |
# Randomly select element from the list | |
alphabet = ["a", "b", "c", "d", "e", "f", | |
"g", "h", "l", "m", "n", "o", "p", "q"] | |
print("The randomly chosen letter is \"{0:s}\"".format(choice(alphabet))) | |
# Using ranrange to select random index | |
randIndex = randrange(0, len(alphabet)) | |
print("The randomly chosen letter is \"{0:s}\"".format(alphabet[randIndex])) | |
print("\n\n---\n\n") | |
# How to transform Lists into other data structures | |
# List of strings | |
list_of_strings = ["Hey", " ", "there", "!"] | |
welcome_message = "".join(list_of_strings) | |
print(welcome_message) | |
# List of integers | |
list_of_integers = [1, 2, 3] | |
print("-".join(str(n) for n in list_of_integers)) | |
print("\n\n---\n\n") | |
# List to a Tuple - Tuples are immutable! | |
alphabet_tuple = tuple(alphabet) | |
print(alphabet_tuple) | |
print("\n\n---\n\n") | |
# List to a Set - Set can contain only unique, hashable items and there is no order | |
my_set = set(["a", "b", "b", "c", "d", "d"]) | |
print(my_set) | |
print("is char \"a\" in set? {0:b}".format("a" in my_set)) | |
print("is char \"f\" in set? {0:b}".format("f" in my_set)) | |
print("\n\n---\n\n") | |
# List(s) to a Dictionary | |
chars = ["a", "b", "c"] | |
foos = ["foo", "bar", "baz"] | |
foo_dict = dict(zip(chars, foos)) | |
print(foo_dict) # {'a': 'foo', 'b': 'bar', 'c': 'baz'} | |
print("\n\n---\n\n") | |
# Working with JSON | |
# Writing to .json file | |
jedi = [ | |
{"name": "Obi-Wan Kenobi", "birth_year": "57BBY", "gender": "male"}, | |
{"name": "Luke Skywalker", "birth_year": "19BBY", "gender": "male"} | |
] | |
with open("jedi.json", "w") as write_file: | |
json.dump(jedi, write_file) | |
# Reading from .json file | |
with open("jedi.json", "r") as read_file: | |
data = json.load(read_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment