Skip to content

Instantly share code, notes, and snippets.

@yuizho
Last active February 12, 2019 15:00
Show Gist options
  • Save yuizho/76dfc54e0566d552f2d3d75dae9d2fcd to your computer and use it in GitHub Desktop.
Save yuizho/76dfc54e0566d552f2d3d75dae9d2fcd to your computer and use it in GitHub Desktop.
## -------------- syntax
l = ['a', 'b']
l[0], l[1] = l[1], l[0]
print(l)
# ['b', 'a']
0 <= 1 <=1
# True
0 <= 4 <=3
# False
# divide with floor
5 // 2
# 2
10**3
# 1000
## -------------- str
'a' * 5
# aaaaa
('0' + 2)[-2:]
# 02
('0' + 22)[-2:]
# 22
'{}: {}'.format('key', 'value')
# key: value
# sum each digit num
str_num = '12567'
sum(map(int, str_num))
# 21
## -------------- list
[0] * 3
# [0, 0, 0]
# ---cout
[1, 2, 3, 2, 2].count(2)
# 3
# ---convert list items
a, b, c = [int(x) for x in ['1', '2', '3']]
# a: 1, b: 2, c:3
# ---☆this way is more better
a, b, c = map(int, ['1', '2', '3'])
list(reversed([1,2,3]))
# [3, 2, 1]
max([1,2,3])
# 3
min([1,2,3])
# 1
# ---get index of max item
l = [1,2,3]
l.index(max(l))
# 2
# ---usage of range
List(range(10))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(2, 10))
# [2, 3, 4, 5, 6, 7, 8, 9]
list(range(2, 10, 3))
# [2, 5, 8]
# ---sort with each item's some value
list = [(5, "e"), (2, "b"), (3, "c"), (1, "a"), (4, "d")]
sorted(list, key = lambda x: x[0])
# [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
## --get max item with each item's some value
list = [(5, "e"), (2, "b"), (3, "c"), (1, "a"), (4, "d")]
max(list, key = lambda x: x[0])
# (5, 'e')
# --grouping with each item value
L = [(1, 'a'), (2, 'b'), (1, 'aa'), (3, 'c'), (3, 'cc'), (1, 'aaa')]
# sorting is necessary
L = sorted(L, key=lambda x: x[0])
[tuple(v) for (k, v) in groupby(L, key=lambda x: x[0])]
# [((1, 'a'), (1, 'aa'), (1, 'aaa')), ((2, 'b'),), ((3, 'c'), (3, 'cc'))]
## -------------- dict
d = {'key1': 'val1'}
d['key1']
# 'val1'
d.get('key1', '')
# 'val1'
d.get('key2', '')
# ''
## -------------- math
import math
math.floor(5/2)
# 2
math.ceil(5/2)
# 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment