1.dict函數
語法:
dict()
dict(**kwarg) dict(mapping, **kwarg) dict(iterable, **kwarg)
第一種:dict()構造一個空字典
h=dict() print(h) #{}
第二種:dict(**kwargs) dict函數需要傳入關鍵字參數。
a=dict(one='1',two='2') print(a) #{'one': '1', 'two': '2'}
第三種:dict(mapping,**kwarg)
b=set([(1,2)]) print(b) #{(1, 2)} b=dict(b) print(b) #{1: 2} c = [(1,'c'), ['c', 1]] c=dict(c) print(c) #{1: 'c', 'c': 1} d = ('ac', set('de')) print(d)#('ac', {'d', 'e'}) d=dict(d) print(d) #{'a': 'c', 'd': 'e'}
第四種:高大上了
e = dict([(['one', 'two'][i - 1], i) for i in (1, 2)]) print(e) #{'one': 1, 'two': 2} f = dict({'one': 1, 'two': 2}.items()) print(f) #{'one': 1, 'two': 2} g = dict(zip(('one', 'two'), (1, 2))) print(g) #{'one': 1, 'two': 2}
2.列表生成式
列表生成式即List Comprehensions,是Python內置的非常簡單卻強大的可以用來創建列表的生成式。
[exp for iter_var in iterable]
首先迭代 iterable 里所有內容, 每一次迭代, 都把 iterable 里相應內容放到 iter_var 中, 再在表達式 exp 中應用該 iter_var 的內容, 最后用表達式的計算值生成一個新的列表.
a=range(1,10) >>> [a*a for a in range(1,10)] [1, 4, 9, 16, 25, 36, 49, 64, 81]
可以使用兩層循環,可以生成全排列:
>>> L = [(x, y) for x in range(2) for y in range(3)] >>> L [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
可以使用判斷語句
>>> c = [x for x in range(10) if x > 5] >>> c [6, 7, 8, 9]
列表生成式也可以使用兩個變量來生成list:
>>> d = {'a': 'A', 'b': 'B', 'c': 'C' } >>> [k + '=' + v for k, v in d.items()] ['a=A', 'b=B', 'c=C']
把一個list中所有的字符串變成小寫:
>>> L = ['I', 'Love', 'Greg'] >>> [s.lower() for s in L] ['i', 'love', 'greg']
雖然列表生成式好用,但需要只是執行一個循環的時候盡量使用循環而不是列表解析, 這樣更符合python提倡的直觀性
當有內建的操作或者類型能夠以更直接的方式實現的, 不要使用列表解析. 例如復制一個列表時, 使用 L1=list(L) 即可, 不必使用: L1=[x for x in L]
如果需要對每個元素都調用並且返回結果時, 應使用 L1=map(f,L), 而不是 L1=[f(x) for x in L].