Python学习之路(三)

Python学习之路(三)

Python Reading Notes : (2006-4-13)
Note One : the powerful Lists

Using Lists as Stacks
 
To add an item to the top of the stack, use append() ,To retrieve an item from the top of the stack, use pop() without an explicit index. For example:
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

Using Lists as Queues

To add an item to the back of the queue, use append() To retrieve an item from the front of the queue, use pop() with 0 as the index. For example:
>>> queue = ["Eric", "John", "Michael"]
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.pop(0)
'Eric'
>>> queue.pop(0)
'John'
>>> queue
['Michael', 'Terry', 'Graham']

Note Two :about Tuples (distinguish between string type and  tuples tpye,especially zero or only one items contained in a tuples )

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)


but if you write a statement like this :
>>> singleton = 'hello'          # it means that you define or construct a string type,not a tuples
>>> singleton
'hello'
 

你可能感兴趣的:(Python学习之路(三))