12 Apr 2009

Python学习笔记 - 6:元组,列表及字典

本文内容主要关于: Python中的三大类型 - 元组(tuple), 列表(list)和字典(dict)

This article would talk about the three important types in Python: tuple, list and dict.


======================================================
25.04.09更新:
今天看到以前写的一个python笔记,更新一下

tuple, list, dict的区别
1. 定义: tuple用()或者直接用分号间隔开一系列元素, list用[], dict用{}
例如: t1=’a’, ‘haha’, 1, 3 或者 t2=(‘a’, ‘haha’,1, 3)
lst1=[‘a’,’haha’, 1, 3], dict1 = {1:’a’, 2:’haha’, 3:1, 4:3}
dict有特殊的构建方法,例如:
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])或者
dict(sape=4139, guido=4127, jack=4098)
2. 操作: tuple一旦定义,不可改变其值; list和dict可以.list可以使用append方法添加元素, dict可直接添加,好像maping一样.
3. 引用: 都必须用[],但是tuple和list用id, dict则必须用键值/key才能索引.
4. 特殊的数据类型set: set([list])可以返回list中所有不重复元素


list当作queue和stack的区别
当queue使用时, 先入先出操作要用pop(0)这个方法; 
当stack使用时,后入先出操作直接使用pop(), 不用指定index会默认return最后一个element.

======================================================

1, 元组(tuple) - 不可改变的列表 ( un-changeable list)

任意对象的序列都可以组成元组,创建一个元组的方法是:用小括号()把这些对象括起来.例如:

Tuple could be constructed by any objects, just simply put all the objects into a brackets().
For example:

>>> t = (1, 2, 3, 'a')
>>> t
(1, 2, 3, 'a')
>>> for i in t:
print i

1
2
3
a
>>>


元组序列索引号从0开始,可以用t[i]来取得元组的第i+1个元素,可以用len()函数得到元组的长度.
元组最大的特点是值不可修改,如果试图修改一个元素的值,会返回错误TypeError,例子如下:

The index of tuple starts from 0, which means you could obtain the value of i+1 element by t[i].
The length of a tuple can be got by function len().
Tuple can be considered as a list, except you can not change the value of its elements. If you try to do so, there would be a TypeError. (See the example below)


>>> t=(1,2,3)
>>> len(t)
3
>>> t
(1, 2, 3)
>>> t[1]
2
>>> t[1] = 'a'

Traceback (most recent call last):
File "", line 1, in 
t[1] = 'a'
TypeError: 'tuple' object does not support item assignment


2, 列表(list) - Python中最常用的类型 (the most popular type in Python)

列表跟元组很相似,都可以由任意对象组成,索引都从0开始;最大(也可能是唯一)的区别是:列表元素的值可以被改变.
使用切片操作可以得到子序列,也可以对序列进行赋值,查找,增加,删除,逆转等操作

List has some properties as tuple, like can be composed by any objects, the index starts from 0.
The most important difference between list and tuple is: the values of lists' elements can be changed.
Some operations can be applied to list are: assign, search, delete, reverse, and so on.

>>> a = range(5)  # generate a list from 0 to 4
>>> a
[0, 1, 2, 3, 4]
>>> a[2]  # get the value of index 2
2
>>> a[3] = 'e'
>>> a
[0, 1, 2, 'e', 4]
>>> a[2:4]  # slice, from index 2 to 4, excluding 4, like[2,4)
[2, 'e']
>>> a[:3]   # slice, from start(0) to 3, excluding 3, like [0,3)
[0, 1, 2]
>>> a[2:]   # slice, from index 2 to the end, like [2,len(a)-1]
[2, 'e', 4]
>>> a[:]    # slice, whole list copy, this method does not return a new object
[0, 1, 2, 'e', 4]
>>> a.append('last')    # append element to the end
>>> a
[0, 1, 2, 'e', 4, 'last']
>>> a.index('e')    # return the index of 'e' of the first occurrence
3
>>> a.index('a')    # return ValueError if 'a' is not in the list

Traceback (most recent call last):
File "", line 1, in 
a.index('a')
ValueError: list.index(x): x not in list
>>> a.reverse()     # reverse the list
>>> a
['last', 4, 'e', 2, 1, 0]
>>> a.remove('e')   # remove the first element with specified value
>>> a
['last', 4, 2, 1, 0]
>>> del a[3]        # remove an element in the specify position
>>> a
['last', 4, 2, 0]
>>> b = ['a','b','c']
>>> a.extend(b)     # extend another list at the end of the current one
>>> a
['last', 4, 2, 0, 'a', 'b', 'c']
>>> a.insert(2,'new item')  # insert an element into the list at the specify position
>>> a
['last', 4, 'new item', 2, 0, 'a', 'b', 'c']
>>> a+= [1,2]       # use + oeration to concatenate lists
>>> a
['last', 4, 'new item', 2, 0, 'a', 'b', 'c', 1, 2]
>>> a.count(2)      # count the number of 2 in the list
2
>>> a.pop()         # return the last element and delete it from the list
2
>>> a.count(2)
1
>>> a
['last', 4, 'new item', 2, 0, 'a', 'b', 'c', 1]
>>> a.sort()        # sort the list, there are some parameters can be found from the document
>>> a
[0, 1, 2, 4, 'a', 'b', 'c', 'last', 'new item']


3, 字典(dict) - Python中的哈希表 (Hash table in Python)

>>> a
{'username': 'xenos', 'blog': 'http://52xenos.blogspot.com/', 'uid': 1} # new dict object
>>> a['username']   # return value according to the key 'username'
'xenos'
>>> a['username'] = 'daniel'    # refine the value of the key 'username'
>>> if a.has_key('username'):   # find if there is a pair "key:value" in the dict, if no, return Wrong
print a['username']
else:
print 'Wrong'

daniel
>>> a.get('username','Wrong')   # same as the if...else... shown above
'daniel'
>>> a.keys()    # return all keys in a list
['username', 'blog', 'uid']
>>> a.values()  # return all values in a list
['daniel', 'http://52xenos.blogspot.com/', 1]

No comments :

Post a Comment