2.1.2.Python crash course
String
print and format的方式
print('My number is: {one}, and my name is: {two}, more {one}'.format(one=num,two=name))
concate
List, Tuple, Dictionary, Set
List
可讀可寫
l = [1,2,3] item = l.pop() l.append('new') 'x' in ['x', 'y', 'z'] //return True x = [(1, 2), (3, 4), (5, 6)] for a, b in x: print(a) print(b)
Tuple
只有初始化時可賦值
t = (1,2,3)
Dictionary
key可以是string或是number
d = {'key1':'item1','key2':'item2'} d.keys() d.items() d.values()
Set
只會儲存唯一值
In : {1,2,3,1,2,1,2,3,3,3,3,2,2,2,1,1,2} Out: {1, 2, 3}
Function
定義function
def my_func(param1='default'):
"""
Docstring goes here.
"""
print(param1)
Map
根據提供的函數對指定序列做映射
def times2(var):
return var*2
seq = [1,2,3,4,5]
map(times2,seq)
lambda expressions
t = lambda var: var*2
t(2)
filter
以傳入的boolean function作為條件函式, iterate所有的sequence的元素並收集 function(元素) 為True的元素到一個List
seq = [1,2,3,4,5]
list(map(lambda var: var*2,seq))
Last updated
Was this helpful?