4. tuple, list 與 dict

最後更新: 2015-04-09

 

目錄

 

 

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)                        # 沒有填 index 時, 正好是 append 的相反

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:

"".join([])

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'])

 



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
  • arbitrary order

定義:

dict = {key1:value1, key2:value2, ... }

沒有 dict 時的做法:

names=["Peter", "Tom"]
user_id=["001", "002"]
print user_id[names.index("Peter")]

dict 的好處:

mydict = {"Peter":"001", "Tom":"002" }
print mydict["Peter"]

建立 Dict

mydict = {}                                                       # 空白的 dict

mydict = {}.fromkeys(['name', 'age'], "unknow")

dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'

returns the value or None

mydict = dict(seq)                                            # 把 seq 轉成 dict

 

dict 中 dict

people = {
    'Peter': {
        'id': '001',
        'addr': 'Here'
    },
    'Tom': {
        'id': '002',
        'addr': 'There'
}

dict.keys()

dict.values()

dict.items()  ##  [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]

 

clear:

d=a

d={}              # 只影響自己

d.clear()         # 會影響 a

 

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

 

get 的好處:

>>> print d.get('name')                    # 如果直接 print d['name'] 就會出 Error
None

 

%

 

 "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.

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. If function is None, the identity function is assumed;

if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables

The iterable arguments may be a sequence or any iterable object; the result is always a list.

Example:

small_letters = map(chr, range(ord('a'), ord('z')+1))

big_letters = map(chr, range(ord('A'), ord('Z')+1))

digits = map(chr, range(ord('0'), ord('9')+1))