The Ultimate Programming Language Syntax Cheat Sheet - 终极编程语法速查 Now include language: python3swift
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 可表示非转义的原始字符串
// 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 iflet 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 { returnInt((x * x + y * y).squareRoot().rounded()) } // if need setter, using: 实时变化的变量同时更改其他变量 var disToOrigin: Int { get { returnInt((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 structLevel{ staticvar 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 = TrueorFalse# 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" forcin 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
// 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) inzip(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) // 交换位置
# python3 my_list = [1, 2, 3, 4] my_list[:i] + my_list[i:] == my_list # True 切片 4in 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
// swift let x = 0 if x > 0 { print("x > 0") } elseif x < 0 { print("x < 0") } else { print("x == 0") } // 三元运算符 let comparison = x > 0 ? " > 0" : " <= 0" // guard // guard is kind of else first if let funcdoSomething(str: String?) { guardlet 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 > 0else'<= 0'
for
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// swift for i in0 ..< 10 { // or 0 ... 9 print(i) }
var sum = 0 for i in0 ..< 10where i % 2 == 1 { sum += i }
var list_a = ["a", "b", "c"] for (i, c) in list_a.enumerated() { print(i, c) }
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 whiletrue { // Do something in loop } //// SPECIFIC //// repeat { // Do something in loop } whiletrue
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 { caselet (x, y, _) where y == x: print("Along the y = x line.") caselet (x, y, _) where y == x * x: print("Along the y = x^2 line.") default: break }
enumWeekday{ case monday, tuesday, wednesday, thursday, friday } enumWeekday: 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" enumFastFoodMenuItem{ case hamburger(numerOfPatties: Int) case fires(size: FryOrderSize) case drink(String, ounces: Int) } enumFryOrderSize{ case large, small } // enum can also be used to create a group of related type methods. enumMath{ staticfuncfactorial(of number: Int) -> Int { return (1...number).reduce(1, *) } } // using Math.factorial(of: 6) to use
#### 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 }
classMyEmptyCalss{
}
1 2 3 4 5 6 7
# python3 defneed_to_do_later(): # TODO (coder name): info pass
classMyEmptyCalss: pass
Functions Defining - 函数定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// swift funcmy_function(arg1_outname arg1: Int, arg2_o arg2: String = "default_val") -> Int { return// return something Int }
// copy-in copy-out and value result funcincrement(_ 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 //// funcnoReture() -> Never { //do something here }
1 2 3 4 5 6 7 8 9 10 11
# python3 defmy_function(arg1, arg2='default_val', *args, **kw): """ docstring """# using print(my_function.__doc__) to show doc return# return something # *args 接受元组 或 list, **kw 接受字典 # 函数注解 - 一般没有意义 defadd_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'
// 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 // 但是这个是通用方法,而之前的写法增加指定的变量 funcincrementCounter(_c: inout Int) { c += 1 }
#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 ** 2for x in range(10)] squares_generator = (x ** 2for x in range(10)) dic_squares = {x: x ** 2for 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
// swift structLocation: CustomStringConvertible{ staticvar 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 mutatingfuncchangeBossName(name: String) { self.boss = name } // type methods staticfuncfactorial(of number: Int) -> Int { return (1...number).reduce(1, *) } // extension can be used to extend a structure extensionLevel{ //code something }
1 2 3 4 5 6 7 8 9
# python 没有结构体, 可以用类来实现, 但是要注意类引用, 不像swift的结构体可以直接赋值就是新拷贝 classLocation: totalLocation = 1# Location.totalLocation def__init__(self, x, y): self.x = x self.y = y
protocolSomeProtocol: InheritedProtocol1, InheritedProtocol2{ var someProperty: Int { getset} funcaMethod(arg1: Double, arg2: String) -> SomeType mutatingfuncchangeIt() 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 classPiece(object): defmove(<args>): raise NotImplementedError(optional_error_message)
classQueen(Piece): defmove(<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)
# 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 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
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
// swift // How to create coutable range for FLOAT (for loop) for i instride(from: 0.5, through: 15.25, by: 0.3) { //do something }
// How to extension Int to get random int extensionInt{ var arc4random: Int { ifself > 0 { returnInt(arc4random_uniform(UInt32(self))) } elseifself < 0 { return -Int(arc4random_uniform(UInt32(self))) } else { return0 } } }
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