Ultimate Syntax Cheat Sheet

The Ultimate Programming Language Syntax Cheat Sheet - 终极编程语法速查
Now include language: python3 swift

Operators - 运算符

Arithmetic operators - 算术运算符

swift python
+ +
- -
* *
/ /
整除 N/A //
取模 % %
N/A **

位运算符

swift python
& &
| |
异或 ^ ^
~ ~
左移 << <<
右移 >> >>

逻辑运算符 & 成员运算符 & 身份运算符

swift python
AND && and
OR || or
NOT ! not
IN in in
NOT IN N/A not in
IS is is
IS NOT N/A is not

String format & Output & input - 输入输出

1
2
3
4
5
6
// swift
let greet = "Hello"
let language = "swift"
print("\(greet) from \(language)") // Interpolation | output
let output = greet + language
// TODO (heaven) input
1
2
3
4
5
6
7
8
# python3
greet = 'Hello'
language = 'python3'
print('{greet} from {language}'.format(greet = 'Hello', language = 'python3')) # output
output = greet + language
my_input = input("Input something:") # input
#### SPECIFIC ####
print(r'\\\all can show') #字符串前加r 可表示非转义的原始字符串

python string format

Data types - 数据类型

basic data types - 基本数据类型

swift python
INT Int int
UINT UInt N/A
FLOAT Float float
DOUBLE Double N/A
BOOL Bool bool
STRING String str
CHARACTER Character N/A
OPTIONAL Optional N/A
COMPLEX N/A complex
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
// swift
var my_int = 1 // var my_int: Int = 1
var my_uint: UInt = 1 // UInt
var my_float: Float = 3.14 // Float
var my_double = 3.14 // Double
var my_bool = true || false // Bool
var my_string = "string" // String
var my_character: Character = "a"
var my_int_optional: Int? = nil // doesn't contain a value
// COMPLEX N/A

//// SPECIFIC ////
// about optional
var my_nil = nil
// TODO
let unwrapperd_my_int_optional = my_int_optional! // force unwrapping
if let my_int_optional = my_int_optional { // optional binding
print(my_int_optional)
} else {
print("no value.")
}
// nil coalescing
var mustHaveResult = my_int_optional ?? 0
// optional chaining
let x: String? = ...
let y = x?.foo()?.bar?.z

// computed properties 实时变化的变量
// in struct Locaiton
var disToOrigin: Int {
return Int((x * x + y * y).squareRoot().rounded())
}
// if need setter, using: 实时变化的变量同时更改其他变量
var disToOrigin: Int {
get {
return Int((x * x + y * y).squareRoot().rounded())
}
set {
// using newValue to set value of x, y here (important)
}
}
// Closures with property initialization 只在初始化时候执行一次
var someProperty: Type = {
// construct the value of someProperty here
return <the constructed value>
}()
// Besides, lazy var variable_name 能定义一个要用到时候才计算的变量
// willSet and didSet, besides, willSet and didSet observers are not called when a property is set during initialization
struct Level {
static var highestLvl = 0
let lvl: Int
var boss: String
var unlocked: Bool {
didSet {
if unlocked && lvl > Level.highestLvl {
Level.highestLvl = lvl
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
# python3
my_int = 1
# UINT N/A
my_float = 3.14
# DOUBLE N/A
my_bool = True or False # and | or | not
my_string = "string" # 'string' | r'show\'
# CHARACTER N/A
# OPTIONAL N/A
my_complex_num = 1 + 2j # complex

#### SPECIFIC ####
my_none = None

Strings 字符串

1
2
3
4
5
6
7
8
9
10
11
let string = "abcd"
for c in string {
print(c)
}
string[string.startIndex] == "a"
string[string.index(before: string.endIndex)] == "d"
string[string.index(string.startIndex, offsetBy: 1)] == "b"
string[string.index(string.endIndex, offsetBy: -2)] == "c"
string[string.index(string.startIndex, offsetBy: 1)..<string.index(string.startIndex, offsetBy: 3)] == "bc"
Array(string) // ["a", "b", "c", "d"]
// TODO string replace in swift
1
2
3
4
5
6
7
8
9
10
string = 'abcd'
for c in string:
print(c)
string[0] == 'a'
string[-1] == 'd'
string[1] == 'b'
string[-2] == 'c'
string[1:3] == 'bc'
list(string) # ['a', 'b', 'c', 'd']
my_string.replace('s', 'a') # "atring"

lists & Arrays - 列表 & 数组

ordered collections of values

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
// swift
var my_list = [1, 2, 3, 4] // [Int]
my_list[..<i] + my_list[i...] == my_list
my_list.contains(4) // true
var empty_list: [Int] = []
my_list.count // 4
my_list.append(5)
my_list.append(contentsOf: [6, 7])
my_list.insert(0, at: 0)
// N/A do not have remove specific element by element
my_list.removeLast()
my_list.remove(at: 0)
my_list.removeAll()
my_list.index(of: 1)
// N/A 没有数一个元素个数的内定函数
my_list.sort() { $0 < $1 }
my_list.reverse()
// swift 不需要浅拷贝
let my_str_list = ["a", "b", "c"]
my_str_list.joined(separator: "") // "abc"
let range_list = Array(0..<10) // create [0,1,2,3,4,5,6,7,8,9]

// Looping techniques 循环技巧
for (i, v) in my_list.enumerated() {
print(i, v)
}

let question = ["qa", "qb", "qc"]
let answer = ["aa", "ab"m "ac"]
for (q, a) in zip(question, answer) {
print("Question is \(question). Answer is \(answer)")
}
//// SPECIFIC ////
my_list.isEmpty
my_list.first
my_list.last
my_list.min()
my_list.max()
let list_slice = my_list[1...2] // using list_slice[1], list_slice[2]
let list_slice = Array(my_list[1...2]) // using list_slice[0], list_slice[1]
my_list.swapAt(0, 3) // 交换位置

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
# python3
my_list = [1, 2, 3, 4]
my_list[:i] + my_list[i:] == my_list # True 切片
4 in my_list # >>> True
empty_list = []
len(my_list) # >>> 4
my_list.append(5) # my_list = [1, 2, 3, 4, 5]
my_list.extend([6, 7])
my_list.insert(0, 0)
my_list.remove(1) # equal to del my_list[0] 通过索引删除
my_list.pop() # pop the last element
my_list.pop(0) # pop the specific element
my_list.clear() # equal to del my_list[:]
my_list.index(1)
my_list.count(1)
my_list.sort(key=lambda x:x)
my_list.reverse()
my_list.copy() #equal to a[:] 浅拷贝
my_str_list = ['a', 'b', 'c']
''.join(my_str_list) # 'abc'
range_list = list(range(10)) #create [0,1,2,3,4,5,6,7,8,9]

# Looping techniques 循环技巧
for i, v in enumerate(my_list):
print(i, v)

question = ['qa', 'qb', 'qc']
answer = ['aa', 'ab', 'ac']
for q, a in zip(question, answer):
print('Question is {0}. Answer is {1}.'.format(q, a))

tuples - 元组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// swift
// swift 元组可以修改其中元素
let my_tuple = (1, 2) // let my_tuple: (Int, Int) = (1, 2)
let my_tuple_element_0 = my_tuple.0
let my_tuple_element_1 = my_tuple.1
// N/A do not have one element tuple in swift
let empty_tuple: (Int, Int)? = nil
let (a, _) = my_tuple

//// SPECIFIC ////
// swift can name the indifidual parts of a tuple
let my_coordinates = (x: 1, y: 2) // or let my_coordinates: (x: Int, y: Int) = (1, 2)
let my_x = my_coordinates.x
let my_y = my_coordinates.y
1
2
3
4
5
6
7
8
9
10
# python3
# python3 元组一旦设定无法更改其中元素
my_tuple = (1, 2)
my_tuple_element_0 = my_tuple[0]
my_tuple_element_1 = my_tuple[1]
only_one_element_tuple = (1,)
empty_tuple = ()
a, _ = my_tuple

#### SPECIFIC ####

sets - 集合

unordered collecition of unique values

1
2
3
4
5
6
// swift
var my_set: Set<Int> = [1, 2]
my_set.contains(1) // true
my_set.insert(3)
my_set.remove(3)
var empty_set: Set<Int> = []

1
2
3
4
5
6
7
8
9
# python3
my_set = set([1,2]) # + - & | ^
1 in my_set # True
my_set.add(3)
my_set.remove(3)
empty_set = set()

#### SPECIFIC ####
a = {x for x in 'abracadabra' if x not in 'abc'} # >>> {'r', 'd'}

dictionaries - 字典

unordered collection of key-value pairs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// swift
var my_dic = ["a": 1, "b": 2]
var my_dic: [String: Int] = ["a": 1, "b": 2]
var empty_dic: [String: Int] = [:]
my_dic.keys.contains("a")
my_dic["a"] ?? 0
my_dic["c"] = 3
my_dic.removeValue(forKey: "a") // same as my_dic["a"] = nil
my_dic.keys
my_dic.values
Array(my_dic)
// TODO 通过 (key, value) 构建字典

// 循环技巧
for (k, v) in my_dic {
print(k, v)
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# python3
my_dic = {'a': 1, 'b': 2}
my_dic_another_init = dict(a=1, b=2)
empty_dic = {}
'a' in my_dic # >>> True
my_dic.get('a', "default_val") # >>> 1
my_dic['c'] = 3
my_dic.pop('a') # >>> 1 and del the key 'a'
my_dic.keys() #get keys
my_dic.values() #get values
my_dic.items() #get (key, value)
dict(my_dic.items()) #通过 (key, value) 构建字典

# 循环技巧
for k, v in my_dic.items():
print(k, v)

Data structure - 数据结构

stack - 栈

1
2
// swift
// TODO
1
2
3
4
# python3
stack = [1, 2, 3]
stack.append(4)
num = stack.pop() # >>> 4

queue - 队列

1
2
// swift
// TODO
1
2
3
4
5
6
7
# python3
# double ended queue
# deque 在首尾两端快速插入和删除而设计
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
queue.popleft()

Control flow - 流程控制

if

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// swift
let x = 0
if x > 0 {
print("x > 0")
} else if x < 0 {
print("x < 0")
} else {
print("x == 0")
}
// 三元运算符
let comparison = x > 0 ? " > 0" : " <= 0"
// guard
// guard is kind of else first if let
func doSomething(str: String?) {
guard let v = str else {
return
}
// use v to do something
}
1
2
3
4
5
6
7
8
9
10
# python3
x = 0
if x > 0:
print('x > 0')
elif x < 0:
print('x > 0')
else:
print('x == 0')
# 三元运算符
comparison = ' > 0' if x > 0 else '<= 0'

for

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// swift
for i in 0 ..< 10 { // or 0 ... 9
print(i)
}

var sum = 0
for i in 0 ..< 10 where i % 2 == 1 {
sum += i
}

var list_a = ["a", "b", "c"]
for (i, c) in list_a.enumerated() {
print(i, c)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# python3
for i in range(1, 10): # [1-9]
print(i)

sum = 0
for i in range(1, 10):
if i % 2 == 1:
sum += i

list_a = ['a', 'b', 'c']
for i, c in enumerate(list_a):
print(i, c)

#### SPECIFIC ####
# for - else
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals {x} * {y}'.format(x = x, y = n // x))
break
else:
print('{n} is a prime number'.format(n = n))
# 循环可以有一个 else 子句;它在循环迭代完整个列表(对于 for )或执行条件为 false (对于 while )时执行,但循环被 break 中止的情况下不会执行。循环的 else 子句在未出现 break 时运行。

while

1
2
3
4
5
6
7
8
// swift
while true {
// Do something in loop
}
//// SPECIFIC ////
repeat {
// Do something in loop
} while true
1
2
3
# python3
while True:
pass

switch

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
// swift
var string = "string"
var mode = "default"
switch mode {
case "l":
print(string.lowercased())
case "u":
print(string.uppercased())
case "c":
print(string.capitalized)
default:
print(string) // if doing nothing, use break
}

//// SPECIFIC ////
let hourOfDay = 12
let timeOfDay: String
switch hourOfDay {
case 0...11:
timeOfDay = "Morning"
case 12...16:
timeOfDay = "Afternoon"
case 17..<24:
timeOfDay = "Evening"
default:
timeOfDay = "INVALID HOUR!"
}

let number = 10
switch number {
case _ where number % 2 == 0:
print("Even")
default:
print("Odd")
}

let coordinates = (x: 1, y: 2, z: 3)
switch coordinates {
case let (x, y, _) where y == x:
print("Along the y = x line.")
case let (x, y, _) where y == x * x:
print("Along the y = x^2 line.")
default:
break
}
1
2
3
4
5
6
7
8
9
# python3
def string_mode(string, mode='default'):
return {
'l': str.lower,
'u': str.upper,
'c': str.capitalize,
't': str.title,
's': str.swapcase
}.get(mode, lambda s:s)(string)

enumeration - 枚举

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
enum Weekday {
case monday, tuesday, wednesday, thursday, friday
}
enum Weekday: Int {
case monday = 1, tuesday, wednesday, thursday, friday
}
let mon = Weekday.monday.rawValue // 1
let fri = Weekday(rawValue: 5)! // friday == Weekday.friday

//// SPECIFIC ////
// swift enum, each state can have its own "associated data"
enum FastFoodMenuItem {
case hamburger(numerOfPatties: Int)
case fires(size: FryOrderSize)
case drink(String, ounces: Int)
}
enum FryOrderSize {
case large, small
}
// enum can also be used to create a group of related type methods.
enum Math {
static func factorial(of number: Int) -> Int {
return (1...number).reduce(1, *)
}
} // using Math.factorial(of: 6) to use
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from enum import Enum, unique
@unique
class Weekday(Enum):
monday = 1
tuesday = 2
wednesday = 3
thursday = 4
friday = 5
mon = Weekday.monday.value
fri = Weekday(5) # Weekday.friday

#### SPECIFIC ####
# another way to call Enum
Weekday = Enum('Weekday', 'monday tuesday wednesday thursday friday')

Iterators - 迭代器

1
2
3
4
5
6
7
8
9
10
11
12
// swift
for element in [1, 2, 3] {
print(element)
}
// can not iterate tuples
for key in ["one": 1, "two": 2].keys {
print(key)
}
for char in "123" {
print(char)
}
// TODO
1
2
3
4
5
6
7
8
9
10
11
# python3
for element in [1, 2, 3]:
print(element)
for element in (1, 2, 3):
print(element)
for key in {'one':1, 'two':2}:
print(key)
for char in "123":
print(char)
for line in open("myfile.txt"):
print(line, end='')

break and continue

1
2
3
// swift
break
continue
1
2
3
# python3
break
continue

pass

1
2
3
4
5
6
7
8
// swift
def need_to_do_later(){
// TODO (coder name): info
}

class MyEmptyCalss {

}
1
2
3
4
5
6
7
# python3
def need_to_do_later():
# TODO (coder name): info
pass

class MyEmptyCalss:
pass

Functions Defining - 函数定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// swift
func my_function(arg1_outname arg1: Int, arg2_o arg2: String = "default_val") -> Int {
return // return something Int
}

// copy-in copy-out and value result
func increment(_ value: inout Int) {
value += 1
}
// after that using & to make clear at the call site
var val = 5
increment(&val) // using copy-in copy-out

//// SPECIFIC ////
func noReture() -> Never {
//do something here
}
1
2
3
4
5
6
7
8
9
10
11
# python3
def my_function(arg1, arg2='default_val', *args, **kw):
""" docstring """ # using print(my_function.__doc__) to show doc
return # return something
# *args 接受元组 或 list, **kw 接受字典
# 函数注解 - 一般没有意义
def add_two_num(a: int, b: int=5) -> int:
print(add_two_num.__annotations__)
return a + b

range(3, 6) == range(*[3, 6]) #same as **kw

built-in functions - 内置函数

1
2
3
4
5
6
7
8
// swift
list.count
list.sorted() { $0 < $1 }
UnicodeScalar("A")
String(describing: UnicodeScalar(65)!) // "\u{041}" 这里用16进制 65 = 0x41
// N/A do not need dir
String(dec_num, radix: 2) // 10进制 转 2进制
Int(bin_str, radix: 2)// 2进制 转 10进制
1
2
3
4
5
6
7
8
9
# python3
len(list)
sorted(list, key=lambda x:x)
ord('A') # >>> 65
chr(65) # >>> 'A'
dir() # 按模块名搜索模块定义,它返回一个字符串类型的存储列表
bin(dec_num) # 10进制 转 2进制
int(bin_str, 2) # 2进制 转 10进制
type('A') # get the type of 'A'

Lambda

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
// swift
// lambda in python is kind of closures in swift
var my_add = { (a: Int, b: Int) in a + b}
var my_add: (Int, Int) -> Int = { $0 + $1 } // same as last one

// for example
var pairs = [(1, "one"), (2, "two"), (3, "three"), (4, "four")]
pairs.sort { $0.1 < $1.1 }
[-3, -2, -1, 1, 2, 3].filter { $0 > 0 }
[1, 2, 3].map { $0 + 10 }
[1, 2, 3].reduce(0) { $0 + $1 } // $0 is init 0, $1 is the num in Array

//// SPECIFIC ////
// closures with no return value
let voidClosure: () -> () = { // -> () can be -> Void
print("This is a void closure.")
}
// using to access the variables and constants from within its own scope
var counter = 0
let incrementCounter = { counter += 1 } // equal to let incrementCounter: () -> () = { counter += 1 }
// let incrementCounter = { counter += 1 } can be write in a function
// 但是这个是通用方法,而之前的写法增加指定的变量
func incrementCounter(_ c: inout Int) {
c += 1
}

let strToInt = ["1", "a", "2"].map { Int($0) } // [Optional(1), nil, Optional(2)]
// flatMap 会把nil的值去掉,直接unwrap
let strToInt = ["1", "a", "2"].flatMap { Int($0) } // [1, 2]
1
2
3
4
5
6
7
8
9
10
# python3
my_add = lambda a, b: a + b

#for example
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda x: x[1])
list(filter(lambda x: x > 0, [-3, -2, -1, 1, 2, 3])) # same as [x for x in [-3, -2, -1, 1, 2, 3] if x > 0]
list(map(lambda x: x + 10, [1, 2, 3])) # same as [x + 10 for x in [1, 2, 3]]
from functools import reduce
reduce(lambda a, b: a + b, [1, 2, 3]) #f(f(1, 2), 3)

List Comprehensions - 列表推导式

1
2
3
4
5
6
7
// swift
var squares = (0..<10).map { $0 * $0}
// swift do not need generator
// can not use list comprehension to create dic in swift

// 交换矩阵行列
// TODO
1
2
3
4
5
6
7
8
9
10
# python3
squares = [x ** 2 for x in range(10)]
squares_generator = (x ** 2 for x in range(10))
dic_squares = {x: x ** 2 for x in range(10)}

#交换矩阵行列
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
transposed = [[row[i] for row in matrix] for i in range(4)]
# same as using zip
transposed = list(map(list, zip(*matrix))) # better usage

Structure (types) - 结构体

structure are value types, no inheritance.

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
// swift
struct Location: CustomStringConvertible {
static var totalLocation = 1 // type property Location.totalLocation
let x: Int // stored properties
let y: Int

init(x: Int, y: Int) { // 如果把init放在 extension里,就不会影响系统自动生成的compiler’s initializer
self.x = x
self.y = y
}

var description: String {
return "(\(x), \(y))"
}
}

//// SPECIFIC ////
// methods in structures cannot change the values of the instance without being marked as mutating
mutating func changeBossName(name: String) {
self.boss = name
}
// type methods
static func factorial(of number: Int) -> Int {
return (1...number).reduce(1, *)
}
// extension can be used to extend a structure
extension Level {
//code something
}

1
2
3
4
5
6
7
8
9
# python 没有结构体, 可以用类来实现, 但是要注意类引用, 不像swift的结构体可以直接赋值就是新拷贝
class Location:
totalLocation = 1 # Location.totalLocation
def __init__(self, x, y):
self.x = x
self.y = y

def __repr__(self):
return "({}, {})".format(self.x, self.y)

Classes and Objects - 类和对象

classes are reference types

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// swift
class MyClass {
var val1: Int
var val2: String

init(val1: Int, val2: String) {
self.val1 = val1
self.val2 = val2
}
func function_1() {
//pass
}
}

//// SPECIFIC ////
Object1 === Object2 // 判断两个引用地址是否相同

1
2
3
4
5
6
7
8
9
10
# python3
class MyCalss: # class MyClass(BaseClassName1, BaseClassName2):
def __init__(self, val1, val2):
self.val1 = val1 #init
self.val2 = val2
def function_1():
pass
# 用于继承的函数
isinstance(obj, int)
issubclass(bool, int)

Protocols - 协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
protocol SomeProtocol: InheritedProtocol1, InheritedProtocol2 {
var someProperty: Int { get set}
func aMethod(arg1: Double, arg2: String) -> SomeType
mutating func changeIt()
init(arg: Type)
}

//// SPECIFIC ////
// Advanced use of Protocols
Hashable
Equatable
CountableRange
Sequence
Collection
1
2
3
4
5
6
7
8
9
# do not have protocols
# but can achieve in this way
class Piece(object):
def move(<args>):
raise NotImplementedError(optional_error_message)

class Queen(Piece):
def move(<args>):
# Specific implementation for the Queen's movements

Tests - 测试

1
// swift
1
2
3
4
# python3
# 为模块提供一个便于测试的用户接口
if __name__ == "__main__":
pass

Reading and Writing Files - 文件读写

1
// swift
1
2
3
4
5
6
7
8
9
10
11
12
# python3
with open('filename', 'w') as f: #'r': 只读 'a': 追加
for line in f:
pass
# other method
f.read(size)
f.readline()
list(f)
f.readlines()
f.write('string')
f.tell()
f.seek(offset, from_what)

JSON 序列化与反序列化

1
2
// swift
// TODO
1
2
3
4
5
6
# python3
import json
my_list = [1, 'simple', 'list']
json.dumps(my_list)
json.dump(my_list, file) # write json type list to file
json.load(file)

python

JSON类型 python
{} dict
[] list
“string” str
12345.56 int/float
true/false True/False
null None

Python json

Modules & Libraries - 模块与库

1
2
// swift
// TODO
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
# python3
import sys
sys.path.append('path you want to add')

import os
os.getcwd() # Return the current working directory
os.chdir('paht') # Change current working directory
os.system('mkdir') # Run the command mkdir

import shutil
shutil.copyfile('data.db', 'archive.db')
shutil.move('/build/executables', 'installdir')

import re
# TODO
import math
import random
random.choice(list) #随机选一个出来
random.sample(range(100), 10) # # sampling without replacement
random.random() # [0 - 1]
random.randrange(6) # int [0 - 5]
import time
import datetime
import timeit
import doctest
from array import array
import collections
from collections import Counter # Counter is very useful
import heapq

Errors and exceptions - 错误与异常

Handling exceptions - 异常处理

1
2
// swift
// TODO
1
2
3
4
5
6
7
8
9
10
11
# python3
try:
pass
except (KindOfError, KindOfError2):
pass
except:
raise # rasing Exceptions
else: #当 try 语句没有抛出异常时, 执行else
pass
finally: #任何情况都执行 (一般用于释放外部资源)
pass

User-defined Exceptions - 定义异常

1
2
// swift
// TODO
1
2
3
4
5
6
# python3
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)

Exception types - 异常类型

1
2
// swift
// TODO
1
2
3
4
5
# python3
ZeroDivisionError #零除错误
NameError #命名错误
TypeError #类型错误
StopIteration #生成器终结时候的错误

Python Built-in Exceptions

Memory

swift
ARC
using Automatic reference counting, 有循环引用漏洞

1
2
3
strong  // (default) as long as anyone, anywhere has a strong pointer to an instance, it will stay in the heap
weak // (only work for optional). if no one else is interested in this, then neither am I, set me to nil in that case. A weak pointer will Never keep an object in the heap.
unowned // don't reference count this; crash if I'm wrong; rarely use, usually only to break memory cycles between objects

python
python采用的是引用计数机制为主,标记-清除和分代收集两种机制为辅的策略, 一样有循环引用的漏洞
java
garbage collection (GC)

Uncategorized - 未归类

以及其他特性汇总

Swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// swift
// How to create coutable range for FLOAT (for loop)
for i in stride(from: 0.5, through: 15.25, by: 0.3) {
//do something
}

// How to extension Int to get random int
extension Int {
var arc4random: Int {
if self > 0 {
return Int(arc4random_uniform(UInt32(self)))
} else if self < 0 {
return -Int(arc4random_uniform(UInt32(self)))
} else {
return 0
}
}
}

Python

template 模版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python3
# -*- coding: utf-8 -*- # usually put this in Header, 为了让中文输出没有乱码,纯英文不需要

""" this comment save in __doc__
AUTHOR :
PURPOSE :
VERSION :
DATE :
INFO :
"""

__author__ = 'Author Name'

# 当前模块直接运行时,运行以下代码
if __name__ == '__main__':
pass

Decorator 装饰器

在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator). 本质上,decorator就是一个返回函数的高阶函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
import functools
import time

def run_time(func):
@functools.wraps(func)
def wrapper(*args, **kw):
start_time = time.time()
result = func(*args, **kw)
end_time = time.time()
print('[Runing time of function `{func}` is {run_time:.6f} sec.]'.format(
func = func.__name__, run_time = end_time - start_time))
return result
return wrapper

@property

@property 装饰器就是负责把一个方法变成属性调用的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Screen:
def __init__(self, width, height):
self._width = width # get set
self._height = height # get

@property
def width(self):
return self._width

@width.setter
def width(self, val):
self._width = val

@property
def height(self):
return self._height

__slots__

使用 __slots__ 限制实例的属性

1
2
class Student:
__slots__ = ('name', 'age')

__slots__ 定义的属性仅对当前类实例起作用,对继承的子类是不起作用的

Tutorial sites - 可参考教学网址


Author: Min Gao

License: CC BY-NC-SA 4.0

如需转载或引用, 请标注出处。