-
Notifications
You must be signed in to change notification settings - Fork 0
/
operators.py
75 lines (58 loc) · 1.5 KB
/
operators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# unpacking operators - https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
a = [8, 2, 6, 5, 4]
[*range(len(a))]
arr1 = range(10)
print(arr1)
[*arr1]
arr2 = range(0, 10, 2)
[*arr2]
arr2 = range(10, 0, -1)
print(*arr2)
values = {'a': 1, 'b': 2}
[*values] # positional arguments
{*values}
{**values} # keywords arguments
# slice [index] and range slice [start:stop:step] operators
arr3 = [1, 2, 3, 4, 5, 6]
arr3[2] # index starts at 0
arr3[-1] # last
arr3[1:3] # take items 2-3, upper bound noninclusive
arr3[0:-1] # take all but the last
arr3[0:-4]
arr3[-5:-2]
arr3[::2]
arr3[::-1]
# modulus: reminder of division
arr = [1, 2, 3, 4, 5]
list(filter(lambda x: x % 2 == 0, arr))
# floor division (no decimals)
x = 13
y = 3
print(x//y)
print(x/y)
print(x % y) # reminder
res, rem = divmod(x, y)
print(f'result:{res}, reminder:{rem}')
# pop: get and remove
arr4 = [5, 3, 6, 2, 10]
arr4.pop(2) # get element by index
arr4 # removed in arr
# enumerate
for index, i in enumerate('pippo'):
print(index, i)
names = ['Bob', 'Alice', 'Guido']
for index, value in enumerate(names):
print(f'{index}: {value}')
names = ['Bob', 'Alice', 'Guido']
for index, value in enumerate(names, 1):
print(f'{index}: {value}')
list(enumerate(names))
# reverse and sorted
arr5 = [1, 2, 3, 4, 5]
list(reversed(arr5))
arr6 = [7, 4, 2, 9, 5]
sorted(arr6)
words = ['banana', 'pie', 'Washington', 'book']
sorted(words, key=len)
tups = [(1, 'd'), (2, 'b'), (4, 'c'), (3, 'c')]
sorted(tups, key=lambda x: x[1])