您的位置:首页 > 编程语言 > Python开发

[Python]list, tuple,dict

2014-05-22 20:22 288 查看
list: arr = [元素]

tuple: arr=(元素)

dictionary: arr = {key:value}

1. list: 普通链表,初始化后可以用过特定方法增加元素。

语法:lst = [元素],下表从0开始

list methods that modify the list:

list.append(object)  append object to the end of the list

list.extend(list) append the items in the list parameter to the list, like list.extend ( [元素] )

list.pop() remove and return the item at the end of the list(option index to remove from anywhere)

list.remove(object) remove the first occurrence of the object; error if not there

list.reverse() reverse the list

list.sort() sort the list from smallest to largest

list.insert(index, object) insert object at the given index, moving items to make room

list methods that do not modify the list

list.count(object) return the number of timesobject occurs in list

list.index(object) return the index of the first occurrence of object; error if not there

mutable: list is mutable, str, int, float, bool are immutable.

aliasing:when two or more objects refer to the same object.

2. tuple 是不可变的list,一旦创建了一个tuple就不能以任何方式改变它

>>> t = ("a","b","c","d")

>>> t

('a', 'b', 'c', 'd')

>>> t[0]

'a'

>>> t[1:3]

('b','c')

注意:

不能向tuple增加元素,tuple没有append,extend,insert等方法。

也不能从tuple中删除元素,tuple没有remove,pop等方法

不能再tuple中查找元素,没有index方法

tuple的好处:

tuple比list的操作速度快。例如定义一个值的常量集并且唯一用它做的就是不断遍历它,那么使用tuple。

tuple可以对不需要修改的数据“写保护”,可以使代码更安全。使用tuple如同拥有一个隐形的assert语句,说明这是一数据常量。如果必须要改变这些值,需要将tuple转换为list:t = list(t); 反之亦然: arr = tuple[arr].

tuple可以作为dictionary的key,list不行,因为dictionary的key必须是不变的。所以只有字符串,整数或其他不可变的tuple才能用作dictionary的key。

3. dictionary可以储存任何值,且允许值的类型不同,如:

>>> dict_arr =  {'a':100, 'b':'boy', 'c':['o', 'p', 'q']}

可以直接给dict_arr增加一个元素,如:

>>> dict_arr['d'] = 'dog'

>>> dict_arr

{'b': 'boy', 'c': ['o', 'p', 'q'], 'a': 100, 'd': 'dog'}

>>> 

遍历dict_arr:

>>> for value in dict_arr:
element = dict_arr.get(value)
if type(element) is type.ListType:
print(value)
for Lvalue in element:
print(Lvalue)
else:
print(element)

dictionary methods:

D.get(key, 0) #同dict[key],多了个没有则返回缺省值,0。[]没有则抛异常

D.keys() #返回字典键的列表

D.values()

D.items()

D.update(dict2) #增加合并字典

D.popitem() #得到一个pair,并从字典中删除它。已空则抛异常

D.clear() #清空字典,同del dict

D.copy() #拷贝字典

D.cmp(dict1,dict2) #比较字典,(优先级为元素个数、键大小、键值大小)

#第一个大返回1,小返回-1,一样返回0

dictionary的复制

dict1 = dict #别名

dict2=dict.copy() #克隆,即另一个拷贝。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: