python-基础-字符串-列表-元祖-字典2

接上:http://www.cnblogs.com/liu-wang/p/8973273.html

3 元组

4 字典

 4.1 字典的介绍

<2>软件开发中的字典

变量info为字典类型:


    info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'} 

说明:

  • 字典和列表一样,也能够存储多个数据
  • 列表中找某个元素时,是根据下标进行的
  • 字典中找某个元素时,是根据'名字'(就是冒号:前面的那个值,例如上面代码中的'name'、'id'、'sex')
  • 字典的每个元素由2部分组成,键:值。例如 'name':'班长' ,'name'为键,'班长'为值

<3>根据键访问值

 info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}

    print(info['name'])
    print(info['address'])

结果:

    班长
    地球亚洲中国北京

若访问不存在的键,则会报错:

>>> info['age']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'age'

在我们不确定字典中是否存在某个键而又想获取其值时,可以使用get方法,还可以设置默认值:

>>> age = info.get('age')
>>> age #'age'键不存在,所以age为None
>>> type(age)
<type 'NoneType'>
>>> age = info.get('age', 18) # 若info中不存在'age'这个键,就返回默认值18
>>> age
18

4.2 字典的常见操作1

 

4.3 字典的常见操作2

5 遍历

6 公共方法

python内置函数

Python包含了以下内置函数

序号 方法 描述
1 cmp(item1, item2) 比较两个值
2 len(item) 计算容器中元素个数
3 max(item) 返回容器中元素最大值
4 min(item) 返回容器中元素最小值
5 del(item) 删除变量

cmp

>>> cmp("hello", "itcast")
-1
>>> cmp("itcast", "hello")
1
>>> cmp("itcast", "itcast")
0
>>> cmp([1, 2], [3, 4])
-1
>>> cmp([1, 2], [1, 1])
1
>>> cmp([1, 2], [1, 2, 3])
-1
>>> cmp({"a":1}, {"b":1})
-1
>>> cmp({"a":2}, {"a":1})
1
>>> cmp({"a":2}, {"a":2, "b":1})
-1

注意:cmp在比较字典数据时,先比较键,再比较值。

len

>>> len("hello itcast")
12
>>> len([1, 2, 3, 4])
4
>>> len((3,4))
2
>>> len({"a":1, "b":2})
2

注意:len在操作字典数据时,返回的是键值对个数。

max

>>> max("hello itcast")
't'
>>> max([1,4,522,3,4])
522
>>> max({"a":1, "b":2})
'b'
>>> max({"a":10, "b":2})
'b'
>>> max({"c":10, "b":2})
'c'

del

del有两种用法,一种是del加空格,另一种是del()

>>> a = 1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = ['a', 'b']
>>> del a[0]
>>> a
['b']
>>> del(a)
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

多维列表/元祖访问

>>> tuple1 = [(2,3),(4,5)] >>> tuple1[0] (2, 3) >>> tuple1[0][0] 2 >>> tuple1[0][2] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: tuple index out of range >>> tuple1[0][1] 3 >>> tuple1[2][2] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range >>> tuple2 = tuple1+[(3)] >>> tuple2 [(2, 3), (4, 5), 3] >>> tuple2[2] 3 >>> tuple2[2][0] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not subscriptable

 7 引用

猜你喜欢

转载自www.cnblogs.com/liu-wang/p/8973643.html