python复习笔记[5]——元组与字典

来源:互联网 发布:妙计旅行知乎 编辑:程序博客网 时间:2024/05/08 08:35


元组:

元组与列表类似,不同之处在于元组的元素不能修改。

元组的常见操作

Python表达式

结果

描述

len((1, 2, 3))

3

计算元素个数

(1, 2, 3) + (4, 5, 6)

(1, 2, 3, 4, 5, 6)

连接

('Hi!',) * 4

('Hi!', 'Hi!', 'Hi!', 'Hi!')

复制

3 in (1, 2, 3)

True

元素是否存在

for x in (1, 2, 3): print x,

1 2 3

迭代

索引元组的元素:

Python 表达式

结果

描述

L[2]

'SPAM!'

读取第三个元素

L[-2]

'Spam'

反向读取;读取倒数第二个元素

L[1:]

('Spam', 'SPAM!')

截取元素

与元组有关的函数:

方法

描述

cmp(tuple1, tuple2)

比较两个元组元素,比较规则:

  1. 如果比较的元素是同类型的,则比较其值,返回结果。
  2. 如果两个元素不是同一种类型,则检查它们是否是数字。

如果是数字,执行必要的数字强制类型转换,然后比较。

如果有一方的元素是数字,则另一方的元素""(数字是"最小的")

否则,通过类型名字的字母顺序进行比较。

  1. 如果有一个列表首先到达末尾,则另一个长一点的列表""
  2. 如果我们用尽了两个列表的元素而且所有元素都是相等的,那么结果就是个平局,就是说返回一个 0

len(tuple)

计算元组元素个数。

max(tuple)

返回元组中元素最大值。

min(tuple)

返回元组中元素最小值。

tuple(seq)

将列表转换为元组。

元组的操作举例:

# empty tuple

tup = ();

 

# create a new tuple and initlization

tup = (1, 2, 3);

 

# add tuple

tup1 = tup + (4, 5, 6);

print tup1[2:];

 

# delete tup

del tup;

print tup1;

 

# tuples share the same operators as lists

print len(tup1);

print tup1 * 4;

print 3 in tup1;

for x in tup1:

   print x;

print tup1[-2];

 

print cmp((1,2,3), tup1);

 

字典:

字典相关的函数:

函数

描述

cmp(dict1, dict2)

比较两个字典元素。

len(dict)

计算字典元素个数,即键的总数。

str(rdict)

输出字典可打印的字符串表示。

type(variable)

返回输入的变量类型,如果变量是字典就返回字典类型。

字典的内置方法:

函数

描述

dict.clear()

删除字典内所有元素

dict.copy()

返回一个字典的浅复制

dict.fromkeys()

创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值

dict.get(key, default=None)

返回指定键的值,如果值不在字典中返回default

dict.has_key(key)

如果键在字典dict里返回true,否则返回false

dict.items()

以列表返回可遍历的(,)元组数组

dict.keys()

以列表返回一个字典所有的键

dict.setdefault(key, default=None)

get()类似,但如果键不存在于字典中,将会添加键并将值设为default

dict.update(dict2)

把字典dict2的键/值对更新到dict

dict.values()

以列表返回字典中的所有值

字典的操作举例:

dict1 = {"A": 100, "B": 80};

print dict1;   #输出:{'A': 100, 'B': 80}

print dict1["A"];   #输出:100

try:

   print dict1["a"];

except:

   print "a not found";   # 输出:a not found

dict1["a"] = "50";

print dict1["a"];   #输出:50

 

del dict1["A"];

print dict1   #输出:{'a': '50', 'B': 80}

 

# remove all keys and values

dict1.clear();

print dict1;   #输出:{}

 

del dict1;

try:

   print dict1;

except:

   print "dict1 not found";   # 输出:dict1 not found

 

dict1 = {"Name" : "Daniel", "Age" : 25, "Name" : "Overwrite"};

print dict1;   #输出:{'Age': 25, 'Name': 'Overwrite'}

 

# Dictionary中Key必须不可变,所以可以用数,字符串或元组充当Key,不能用列表作为Key

 

print type(dict1);   #输出:<type 'dict'>

print cmp(dict1, {});   #输出:1

print cmp(dict1, dict1);   #输出:0

print len(dict1);   #输出:2

print dict1.keys();   #输出:['Age', 'Name']

print dict1.values();   #输出:[25, 'Overwrite']

print dict1.items();   #输出:[('Age', 25), ('Name', 'Overwrite')]

print str(dict1);   #输出:{'Age': 25, 'Name': 'Overwrite'}

 

dict2 = dict1.fromkeys(["a", "b"]);

print dict2;   #输出:{'a': None, 'b': None}

 

print dict2.has_key("a");   #输出:true

print dict2.get("c", 10);   #输出:10

56 0