DUST

Do the things I want to do

Python 笔记(3) -- More on Data Structures

1. More on List

    a) Functional Programming Tools

    filter(function, sequence):  returns a sequence consisting of those items from the sequence for which function(item) is true.

    如果sequence是string或tuple,则filter返回string或tuple;否则返回list

 

 

>>> def f(x): return x % 2 != 0 and x % 3 != 0

>>> filter(f, range(225))
[
571113171923]

 

     map(function, sequence): calls function(item) for each of the sequence's items and returns a list of the return values. 

 

>>> def cube(x): return x*x*x

>>> map(cube, range(111))
[
1827641252163435127291000]

 

     可以传多个sequence。但如果sequences长度不同,则短sequence对应于长sequence的items被视为None. => 如果做与None不符的操作会产生错误.

 

>>> seq = range(8)
>>> def add(x, y): return x+y

>>> map(add, seq, seq)
[0, 
2468101214]

 

     reduce(function, sequence): returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on.

 

>>> def add(x,y): return x+y

>>> reduce(add, range(111))
55

 

     b) List Comprehensions

     一种比map(), filter() and/or lambda 更为“精妙”的产生List的方法。

          List Comprehension: [expression for ... [for ...][ if...]]. [for ...][ if...]] means 0 or more

     如果expression是一个tuple,则必须括起来

 

>>> vec = [246]
>>> [3*for x in vec if x > 3]
[
1218]
>>> [[x,x**2for x in vec] #expression is tuple
[[24], [416], [636]]
>>> [(x, x**2for x in vec]
[(
24), (416), (636)]

# operate on two lists
>>> vec1 = [246]
>>> vec2 = [43-9]
>>> [x+for x in vec1 for y in vec2]
[
65-787-5109-3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[
812-54]

 

2.  del statement

     通过a) index,b) slices 删除list中的元素。也可删除变量

 

3. Tuple

     A tuple consists of a number of values separated by commas.

     Tuple允许嵌套,单个tuple输入时无需加括号,但如果作为一个元素用在其他表达式中,则需要加括号。

     与string一样,tuple中的元素值也是不可更改的,但tuple可以包含mutable的对象,如list.

 

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
(
'hello',)

 

     tuple packing: such as t = 12345, 54321, 'hello!', the values 12345, 54321 and 'hello!' are packed together in a tuple.

   sequence unpacking: such as x, y, z = t. 左边变量列表中的元素个数必须与右边的tuple中元素个数相同

   multiple assignment是tuple packing和sequence unpacking的组合

 

4. Sets

     元素不允许重复的无序集合。支持并集,交集,差集和对称差集(symmetric difference)等集合操作

 

>>> basket = ['apple''orange''apple''pear''orange''banana']
>>> fruit = set(basket)               # create a set without duplicates
>>> fruit
set([
'orange''pear''apple''banana'])
>>> 'orange' in fruit                 # fast membership testing
True
>>> 'crabgrass' in fruit
False

>>> # Demonstrate set operations on unique letters from two words

>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
set(['a''r''b''c''d'])
>>> a - b                              # letters in a but not in b
set(['r''d''b'])
>>> a | b                              # letters in either a or b
set(['a''c''r''d''b''m''z''l'])
>>> a & b                              # letters in both a and b
set(['a''c'])
>>> a ^ b                              # letters in a or b but not both
set(['r''d''b''m''z''l'])

 

5. Dictionaries

     dictionary = {key:value, key:value,...}

     dictionaries中,key可以为string,number,tuple(tuple中不能包含mutable的对象,如list)。key是唯一的,当对其中一个key对应的元素赋值时,之前保存的值会被冲掉。用del可以删除dict中的key:value元素,如del dict["key1"]

     key()返回包含所有key的list,无序。

     has_key() or in 查看某个key是否包含在dict中

    dict() 从key-value以tuple方式存储的list中构建dictionary

 

>>> dict([('sape'4139), ('guido'4127), ('jack'4098)])
{
'sape'4139'jack'4098'guido'4127}
>>> dict([(x, x**2for x in (246)])     # use a list comprehension
{24416636}

>>> dict(sape=4139, guido=4127, jack=4098)
{
'sape'4139'jack'4098'guido'4127}

 

6. Looping Techniques

     a) dictionaries

          用 iteritems() 同时获得key和value

     b) one sequence

          用 enumerate() 同时获得index和value 

     c) two or more sequences

          zip(seq1, seq2...)

     d) a sequence in reversed

          reversed(seq)

     e) a sequence in sorted

          sorted(seq): 生成一个新的有序的sequence

 

#dictionary
>>> knights = {'gallahad''the pure''robin''the brave'}
>>> for k, v in knights.iteritems():
     
print k, v

gallahad the pure
robin the brave
# a sequence
>>> for i, v in enumerate(['tic''tac''toe']):
     
print i, v

0 tic
1 tac
2 toe
# two or more sequences
>>> questions = ['name''quest''favorite color']
>>> answers = ['lancelot''the holy grail''blue']
>>> for q, a in zip(questions, answers):
     
print 'What is your %s?  It is %s.' % (q, a)
    
What 
is your name?  It is lancelot.
What 
is your quest?  It is the holy grail.
# a sequence in reversed order
>>> for i in reversed(xrange(1,10,2)):
     
print i

9
7
5
3
1
# a sequence in sorted order
>>> basket = ['apple''orange''apple''pear''orange''banana']
>>> for f in sorted(set(basket)):
     
print f
     
apple
banana
orange
pear

posted on 2008-09-08 16:32  should  阅读(404)  评论(0编辑  收藏  举报

导航