python中字典的概念:
一.字典的概念:
dictionary(字典)是除列表以外python中最灵活的数据类型,字典同样可以用来存储多个数据.通常用于存储描述一个物体的相关信息
二.和列表的区别:
列表是有序的对象集和
字典是无序的对象集和
三.字典用{ }定义
四.注意:
字典使用键值对存储数据,键值对之间使用,分隔
键key是索引
值value是数据
键和值之间使用;分隔
键必须是唯一的(因为我们必须通过键来找到数据)
值可以取任何数据类型,但键只能使用字符串,数字或元组
五.字典的定义:
字典是一个无序的数据集和,使用print函数输出字典时,
通常输出的顺序和定义的顺序是不一致的
六.字典在python中的应用:
1.字典的取值,增加,修改,删除
# 字典是一个无序的数据集合,使用print输出字典的
#时候通常和定义的数据顺序不一样
message = {'name':'tom',
'age':18,
'height':1.85,
'weight':75.5}
print message
# 1.取值:
print message['name']
# 2.增加:
message['sex'] = 'man'
print message
# 3.修改:
message['age'] = 19
print message
# 4.删除:
message.pop('name')
print message
2.字典中查找键值对数量与合并字典
message = {'name':'tom',
'age':18,
'height':1.85,
'weight':75.5}
# 1.统计建值对的数量:
print len(message)
# 2.合并字典:
#字典的自定义建是可变的也是唯一的
#相同键更新,不同键合并
temp_dict = {'height':1.90,
'sex':'man'}
message.update(temp_dict)
print message
3.字典的for循环
message_dict = {'name':'harry',
'qq':'1234567',
'phone':'765467'}
for k in message_dict:
print '%s - %s' % (k,message_dict[k])
4.FOR嵌套使用
card_list=[{'name':'zhangsan','qq':'4578567','phone':'9876664'},
{'name':'sfwf','qq':'345678','phone':'645674764'}]
for card_info in card_list:
print card_info
for k in card_info:
print '%s --> %s' % (k, card_info[k])
python中元组的概念:
一.元组的概念:
Tuple(元组)与列表相似,不同之处在于元组的元素不能修改
元组表示多个元素组成的序列
元组在python开发中,有特定的应用场景
用于存储一串信息,数据之间使用,分隔
二.元组用( )定义:
列表中通常保存相同类型的数据,而元组中通常保存不同类型的数据
三.元组在python中的应用:
info_tuple = ('李四', 18, 1.75, '张三', '张三')
# 1.取值和取索引
print info_tuple[0]
print info_tuple.index('张三')
# 2.统计计数(有几个张三)
print info_tuple.count('张三')
# 3.统计元组中包含元素的个数
print len(info_tuple)
# 4.在元组中取值应用:
info_tuple = ('小明', 18, 1.90)
print '%s 的年龄是:%d 身高是:%.2f' % info_tuple
Python中字符串的应用:
一.字符串的查找与统计:
hello_str = 'hello python llo'
# 1.统计字符串长度
print len(hello_str)
# 2.统计某一个小的字符串(子字符串)出现的次数,没有的显示为0
print hello_str.count('llo')
# 3.某一个子字符串出现的位置(如果有重复的字符,现实第一个的位置)
print hello_str.index('llo')
# 使用index()查找的时候,字符串不存在会出现报错
print hello_str.index('ww')
二.判断字符串中的元素结构:
# 1.判断字符串是否只包含数字
num_str = '1'
print num_str
print num_str.isdigit()
# 2.判断是否以指定的字符串开始
hello_str = 'hello python'
print hello_str.startswith('hello')
# 3.判断字符串是否以指定的字符串结束
print hello_str.endswith('bb')
# 4.查找指定字符串
# 如果查找的指定字符串不存在 程序不会报错 会返回-1
print hello_str.find('lp')
#5.替换字符串
print hello_str.replace('python','world')
print hello_str
# 6.判断字符串是否有空格 /t(制表符) /n(换行符)
null = ' '
print null.isspace()
三.利用索引值进行切片:
格式:字符串/列表/元组【开始索引:结束索引:步长(有跳跃有间隔的对字符串切片)】
倒叙索引:如果一个字符串/列表/元组很长很长,使用倒序索引很方便
最后一个索引的倒叙索引是:-1
注意:
1.指定的区间属于左闭右开型,从起始位置开始,到结束位置的前一位(不包含结束位本身)
2.从头开始,开始索引数字可以省略,冒号不能省略
3.到末尾结束,结束索引数字可以省略,冒号不能省略
4.步长默认为1
# 建立一个字符串
num_str = '0123456789'
# 从索引为2处取到索引为5前
print num_str[2:5]
# 从索引为2处取到索引为6前
print num_str[2:6]
# 从索引为2处取到字符串末尾
print num_str[2:]
# 从开头处取到索引为9前
print num_str[:9]
# 取出全部字符串
print num_str[:]
# 从开头取到索引为10前,步长为2
print num_str[0:8:2]
# 取出步长为2的全部字符串
print num_str[::2]
# 取倒数第一个字符
print num_str[-1]
# 从索引为2取到索引为-1前
print num_str[2:-1]
# 让字符串整体倒序
print num_str[-1::-1]