最後更新: 2020-12-11
目錄
list
Usage:
mylist = ["Linux", "Mac OS" , "Windows"]
String to List:
list('Hello')
['H', 'e', 'l', 'l', 'o']
for 與 if
for var in list:
if 'curly' in list:
range
range(n) 輸出 0, 1, ... n-1
range(a, b) 輸出 a, a+1, ... b-1
max 與 min
num=range(10)
max (num)
min (num)
del
var = 6
del var
----
list = ['a', 'b', 'c', 'd']
del list[0] # Delete first element
del list[-2:] # Delete last two elements
----
dict = {'a':1, 'b':2, 'c':3}
del dict['b'] # Delete 'b' entry
count:
>>> x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
>>> x.count(1)
2
結合:
c=a+b
a.extend(b) # 相當於 +=
組合 zip:
names = ['apple', 'orange', 'banana', 'pear']
color = ['red', 'orange', 'yellow', 'green']
zip(names, color)
result:
[('apple', 'red'), ('orange', 'orange'), ('banana', 'yellow'), ('pear', 'green')]
再把 list 轉化為 dict
dict(zip(names, color))
remove
list.remove(elem)
>>> x = ['a', 'b', 'c', 'a']
>>> x.remove('a')
>>> x # ['b', 'c', 'a'] 只移除第一個
# Raises ValueError if the value is not present.
Code:
mylist=["A","B","C","A"]
for myitem in mylist:
if mylist.count(myitem) > 1:
mylist.remove(myitem)
print myitem
./test.py
A
append 與 pop:
list.append(elem)
沒有 return 的 !
list.pop(index)
return 被 pop 那個 item, 沒有指定 index 時, Default: index=-1
-1 = 由頭開始
0 = 順序開始
N = 第幾個.
list.insert(index, elem) #
list.index(elem)
sorting
list.sort()
list.sorted() # 有 reture
ist.reverse()
sorted(strs, key=MyFn, cmp=cmpFn)
Default cmp: cmp(a, b)
strs = ['ccc', 'aaaa', 'd', 'bb']
print sorted(strs, key=len) ## ['d', 'bb', 'ccc', 'aaaa']
print sorted(strs, key=str.lower) ## ['aa', 'BB', 'CC', 'zz']
join:
# 用空格將 a, b, c join 埋
" ".join(["a", "b"," c"])
in:
mylist = [1,2,3,4,'a','b','c'] 'a' in mylist # True
2-Level
arr = [] arr.append([]) arr[0].append('aa1') arr[0].append('aa2')
OR
arr = [] arr.append(['aa1', 'aa2'])
Example
>>> foo = ['bar' for _ in range(10)] >>> print foo ['bar', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar', 'bar']
tuple
特性:
- fixed size
- immutable
mytuple = (1, 2, 'hi')
mytuple[2]="bye" ## 唔得
mytuple = (1, 2, 'bye') ## this works
(x, y, z) = (42, 13, "hike")
tuple([1, 2, 3])
dict
- Group values into a structure
- Refer to each value by name - key
- Arbitrary order
定義 dict:
dict = {key1:value1, key2:value2, ... }
兩個 list 合成 dict
names = ["Peter", "Tom", "May"] foods = ["apple", "orange", "pear"] mydict = dict(zip(names, foods)) # Test print(mydict["Peter"]) # apple
建立 Dict
空白的 dict
mydict = {}
fromkeys
x = ('key1', 'key2', 'key3') y = 0 mydict = {}.fromkeys(x, y) print mydict # {'key3': 0, 'key2': 0, 'key1': 0}
key = value
dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega'
把 seq 轉成 dict
mydict = dict(seq)
dict 中 dict
people = { 'Peter': { 'id': '001', 'addr': 'Here' }, 'Tom': { 'id': '002', 'addr': 'There' }
keys(), values(), items()
dict.keys()
dict.values()
dict.items()
{"a":"alpha", "o":"omega", "g":"gamma"} 轉成了 [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]
應用
mydict = {"a":"alpha", "o":"omega", "g":"gamma"} for i in mydict: print(i) # 一行一個 a o g for i in mydict.items(): print(i) # 一行一個 ('a', 'alpha') ('o', 'omega') ('g', 'gamma')
clear:
# {} 與 .clear()
a = {"x", "y"}
b = a
b={} # 只影響自己 "b"
b.clear() # 連 a 也會影響, print a 只有 None
copy 與 deepcopy
x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
y = x.copy()
y['machines'].remove('bar') # 雖然只對 y 操作, 但仍會影響 x
解決方法:
from copy import deepcopy
y = x.deepcopy()
Output:
>>> d.has_key('name') # 如果直接 print d['name'] 就會出 Error
0
dict.get 的好處:
>>> print d.get('name') # 如果直接 print d['name'] 就會出 Error
None
Default Value
#!/usr/bin/python myDict={'A':1, 'B':2, 'C':3} print(myDict['D'])
output
Traceback (most recent call last): File "./test.py", line 5, in <module> print(myDict['D']) KeyError: 'D'
# Set default value
print(myDict.get('D', 'Null'))
%
"Peter 's user_id is %(Peter)s." % mydict
>>> d = {'x': 1, 'y': 2}
>>> d.pop('x')
1
>>> d
{'y': 2}
用 dict 來 update dict
>>> x = {'name': 'peter'}
>>> d.update(x)
map(function, iterable, ...)
Apply function to every item of iterable and return a list of the results
Syntax: map(fun, iter ...)
the result is always a List(py2), Iterator(py3)
If additional iterable arguments are passed,
function must take that many arguments and is applied to the items from all iterables in parallel.
If one iterable is shorter than another it is assumed to be extended with None items.
Example:
[1]
strip_list = map(str.strip, lines)
str.strip # unbound method
[2]
lines1=(1,2,3) lines2=(4,5,6) def add(x,y): return x + y print map(add,lines1,lines2)
Remark
lists comprehensions:
strip_list = [item.strip() for item in lines]
reduce()
Applies function of two arguments cumulatively to the items of iterable, from left to right,
so as to reduce the iterable to a single value.
Syntax: reduce (function, iterable)
i.e.
reduce(lambda x, y: x+y, [1, 2, 3, 4])
10 # ((1+2)+3)+4)
filter()
Returns a sequence from those elements of iterable for which function returns True.
Syntax: filter (function, iterable)
i.e.
>>> def f(x): ... if x > 0: ... return x >>> filter(f, [-1, 0, 1]) [1]
set()
介紹:
Set 是無序及元素不重複的集合
e.g.
myset = set("[email protected]") print myset set(['@', 'c', 'e', 'm', 'o', '.', 's', 't'])
運算:
- in 元素是否在集合中
- & 交集
- | 聯集
- ^ XOR
- > 左是否為右的父集
- - 差
{} 不是空的 set 來. 如果要建立空的 set, 那要用 set()
測試:
>>> set1 = {'AAA', 'BBB'} >>> set2 = {'AAA', 'CCC', 'DDD'} >>> 'AAA' in set1 True >>> set1 & set2 {'AAA'} >>> set1 | set2 {'AAA', 'BBB', 'CCC', 'DDD'} >>> set1 - set2 {'caterpillar'} >>> set1 ^ set2 {'BBB', 'CCC', 'DDD'} >>> set1 > set2 False >>> set1 < set2 False >>>
# 加元素
s.add('e')
# 當set與list混在一起時用"&","|"
# &
admins.intersection(users)
# |
admins.union(users)
# 詳見
>>> dir(set()