(1) Swapping values
x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)
(2) Combining a list of strings into a single one
sentence_list = ["my", "name", "is", "George"]
sentence_string = " ".join(sentence_list)
print(sentence_string)
fruits = ['apple', 'mango', 'orange']
print(', '.join(fruits))
numbers = [1, 2, 3, 4, 5]
print(', '.join(map(str, numbers)))
items = [1, 'apple', 2, 3, 'orange']
print(', '.join(map(str, items)))
row = [100, "android", "ios", "blackberry"]print(', '.join(str(x) for x in row))print(*row, sep=', ')
(3) Splitting a string into a list of substrings
sentence_string = "my name is George"
sentence_string.split()
print(sentence_string)
(4) Initialising a list filled with some number
[0]*1000 # List of 1000 zeros
[8.2]*1000 # List of 1000 8.2's
(5) Merging dictionaries
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
(6) Reversing a string
name = "George"
name[::-1]
(7) Returning multiple values from a function
def get_a_string():
a = "George"
b = "is"
c = "cool"
return a, b, c
sentence = get_a_string()
(a, b, c) = sentence
(8) List comprehension
a = [1, 2, 3]
b = [num*2 for num in a] # Create a new list by multiplying each element in a by 2
(9) Iterating over a dictionary
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key, value in m.items():
print('{0}: {1}'.format(key, value))
(10) Iterating over list values while getting the index too
m = ['a', 'b', 'c', 'd']
for index, value in enumerate(m):
print('{0}: {1}'.format(index, value))
(11) Initialising empty containers
a_list = list()
a_dict = dict()
a_map = map()
a_set = set()
(12) Removing useless charaters on the end of your string
name = " George "
name_2 = "George///"
name.strip() # prints "George"
name_2.strip("/") # prints "George"
(13) Find the most frequent element in a list
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
### Use Counterfrom collections import Counter
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 occurrenceprint(dict(cnt.most_common(2)))
str_lst = ['blue', 'red', 'green', 'blue', 'red', 'red', 'green']print(dict(Counter(str_lst)))
(14) Check the memory usage of an object
import sys
x = 1
print(sys.getsizeof(x))
(15) Convert a dict to XML
from xml.etree.ElementTree import Elementdef dict_to_xml(tag, d):
'''
Turn a simple dict of key/value pairs into XML
'''
elem = Element(tag)
for key, val in d.items():
child = Element(key)
child.text = str(val)
elem.append(child)
return elem
(16) 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))
(17) 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)
(18) Merge Dictionaries
d1 = {'a': 1}
d2 = {'b': 2}print(dict(d1.items() | d2.items()))
print({**d1, **d2})d1.update(d2)
print(d1)
(19) 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}")# another behaviorfrom itertools import zip_longestcolors = ["red", "green", "yellow", "blue"]
codes = [1, 2, 3, 4, 5, 6]for color, code in zip_longest(colors, codes):
print(f"{code}, {color}")for color, code in zip_longest(colors, codes, fillvalue='Nothing'):
print(f"{code}, {color}")
Комментарии
Отправить комментарий