丁祖平

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

一. 前言

1. 什么是数据:

x = 10,10就是我们要存储的数据

2. 为何数据要分不同的类型

数据是用来表示状态的, 不同的状态就应该用不同类型的数据去表示

3. 数据类型

数字(整型、长整型、浮点型、复数)

字符串

字节串(在介绍字符编码时介绍字节bytes类型)

列表

元祖

字典

集合

4. 接下来我按照以下几点展开数据类型的学习

#======================================基本使用======================================
# 1. 用途
# 2. 定义方式
# 3. 常用操作 + 内置的方法

#======================================该类型总结====================================
# 存一个值 或 存多个值
# 有序 或 无序
# 可变 或 不可变
(1. 可变:值变,id不变,可变==不可hash; 2. 不可变:值变, id就变,不可变==可hash)

 

二、 数字

整型和浮点型

# 整型int
    作用:年纪,等级,身份证号,qq号等整型数字相关
    定义:
        age=10 #本质是age=int(10)

# 浮点型float
    作用:薪资、身高、体重、体质参数等浮点数相关
    salary=3000.3  # 本质salary=float(3000.3)

其他数字类型(了解)

# 长整型(了解)
在python2中有,在python3中没有长整型的概念

# 复数(了解)
x = 1-2j
x.real
1.0
x.imag
-2.0

三、 字符串

#作用:名字,性别,国籍,地址等描述信息

#定义:在单引号\双引号\三引号内,由一串字符组成
name='dingding'

#优先掌握的操作:
#1、按索引取值(正向取+反向取) :只能取
#2、切片(顾头不顾尾,步长)
#3、长度len
#4、成员运算in和not in

#5、移除空白strip
#6、切分split
#7、循环

需要掌握的操作

#1、strip,lstrip,rstrip
#2、lower,upper
#3、startswith,endswith
#4、format的三种玩法
#5、split,rsplit
#6、join
#7、replace
#8、isdigit
#strip
name='*egon**'
print(name.strip('*'))
print(name.lstrip('*'))
print(name.rstrip('*'))

#lower,upper
name='egon'
print(name.lower())
print(name.upper())

#startswith,endswith
name='alex_SB'
print(name.endswith('SB'))
print(name.startswith('alex'))

#format的三种玩法
res='{} {} {}'.format('egon',18,'male')
res='{1} {0} {1}'.format('egon',18,'male')
res='{name} {age} {sex}'.format(sex='male',name='egon',age=18)

#split
name='root:x:0:0::/root:/bin/bash'
print(name.split(':')) #默认分隔符为空格
name='C:/a/b/c/d.txt' #只想拿到顶级目录
print(name.split('/',1))

name='a|b|c'
print(name.rsplit('|',1)) #从右开始切分

#join
tag=' '
print(tag.join(['egon','say','hello','world'])) #可迭代对象必须都是字符串

#replace
name='alex say :i have one tesla,my name is alex'
print(name.replace('alex','SB',1))

#isdigit:可以判断bytes和unicode类型,是最常用的用于于判断字符是否为"数字"的方法
age=input('>>: ')
print(age.isdigit())
# 其他操作(此操作了解即可)

#1、find,rfind,index,rindex,count
#2、center,ljust,rjust,zfill
#3、expandtabs
#4、captalize,swapcase,title
#5、is数字系列
#6、is其他


#find,rfind,index,rindex,count
name='egon say hello'
print(name.find('o',1,3)) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
# print(name.index('e',2,4)) #同上,但是找不到会报错
print(name.count('e',1,3)) #顾头不顾尾,如果不指定范围则查找所有

#center,ljust,rjust,zfill
name='egon'
print(name.center(30,'-'))
print(name.ljust(30,'*'))
print(name.rjust(30,'*'))
print(name.zfill(50)) #用0填充

#expandtabs
name='egon\thello'
print(name)
print(name.expandtabs(1))

#captalize,swapcase,title
print(name.capitalize()) #首字母大写
print(name.swapcase()) #大小写翻转
msg='egon say hi'
print(msg.title()) #每个单词的首字母大写

#is数字系列
#在python3中
num1=b'4' #bytes
num2=u'4' #unicode,python3中无需加u就是unicode
num3='四' #中文数字
num4='Ⅳ' #罗马数字

#isdigt:bytes,unicode
print(num1.isdigit()) #True
print(num2.isdigit()) #True
print(num3.isdigit()) #False
print(num4.isdigit()) #False

#isdecimal:uncicode
#bytes类型无isdecimal方法
print(num2.isdecimal()) #True
print(num3.isdecimal()) #False
print(num4.isdecimal()) #False

#isnumberic:unicode,中文数字,罗马数字
#bytes类型无isnumberic方法
print(num2.isnumeric()) #True
print(num3.isnumeric()) #True
print(num4.isnumeric()) #True

#三者不能判断浮点数
num5='4.3'
print(num5.isdigit())
print(num5.isdecimal())
print(num5.isnumeric())
'''
总结:
    最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
    如果要判断中文数字或罗马数字,则需要用到isnumeric
'''

#is其他
print('===>')
name='egon123'
print(name.isalnum()) #字符串由字母或数字组成
print(name.isalpha()) #字符串只由字母组成

print(name.isidentifier())
print(name.islower())
print(name.isupper())
print(name.isspace())
print(name.istitle())

练习

# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = " aleX"
# 1)    移除 name 变量对应的值两边的空格,并输出处理结果
a = name.strip()
print(a)

# 2)    判断 name 变量对应的值是否以 "al" 开头,并输出结果if name.startswith(name):
    print(name)
else:
    print("no")

# 3)    判断 name 变量对应的值是否以 "X" 结尾,并输出结果if name.endswith(name):
    print(name)
else:
    print("no")

# 4)    将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
name = 'aleX'
print(name.replace('l', 'p'))

# 5)    将 name 变量对应的值根据 “l” 分割,并输出结果。
print(name.split('l'))

# 6)    将 name 变量对应的值变大写,并输出结果print(name.upper())

# 7)    将 name 变量对应的值变小写,并输出结果print(name.lower())

# 8)    请输出 name 变量对应的值的第 2 个字符?
print(name[1])

# 9)    请输出 name 变量对应的值的前 3 个字符?
print(name[:3])

# 10)    请输出 name 变量对应的值的后 2 个字符?print(name[-2:])

# 11)    请输出 name 变量对应的值中 “e” 所在索引位置?print(name.index('e'))

# 12)    获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
a = name[:-1]
print(a)

四、 列表

# 作用: 多个装备, 多个爱好, 多门课程, 多个女朋友等

# 定义: []内可以有多个任意类型的值, 逗号分隔
# 本质是: my_girl_friends =list([...])
my_girl_friends = ['fengjie', 'peiqi', 'qiaozhi', 'furongjiejie']

# 优先掌握的操作
# 1. 按索引存取值(正向存取+反向存取):即可存也可以取
# 2. 切片(顾头不顾尾,步长)
# 3. 长度
# 4. 成员运算in和not in
# 5、追加
# 6、删除
# 7、循环
# ps:反向步长
l = [1,2,3,4,5,6]

# 正向步长
l[0:3:1] #[1,2,3]

# 反向步长
l[2::-1]   #[3,2,1]

# 列表翻转
l[::-1] #[6, 5, 4, 3, 2, 1]
1. 有列表data=['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量

2. 用列表模拟队列

3. 用列表模拟堆栈

4. 有如下列表,请按照年龄排序(涉及到匿名函数)
l=[
    {'name':'alex','age':84},
    {'name':'oldboy','age':73},
    {'name':'egon','age':18},
]
答案:
l.sort(key=lambda item:item['age'])
print(l)

 五、 元祖

# 作用: 存多个值,对比列表来说,元祖不可变(是可以当做字典的key的), 主要是用来读

# 定义: 与列表类型比,只不过是将[]换成了()
age = (11,22,33,44,55) 的本质是 age = tuple((11,22,33,44,55))

# 优先掌握的操作
# 1.按索引取值(正向取+反向取): 只能取
# 2.切片(顾头不顾尾, 步长)
# 3.长度
# 4.成员运算 in 和 not in
# 5.循环

练习

#简单购物车,要求如下:
# 实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
} 

练习的代码

msg_dic = {
    'apple': 10,
    'tesla': 100000,
    'mac': 3000,
    'lenovo': 30000,
    'chicken': 10,
}

goods_l = []
while True:
    for key, item in msg_dic.items():
        print('name:{name} price:{price}'.format(price=item, name=key))
    choice = input('商品>>: ').strip()
    if not choice or choice not in msg_dic:
        continue
    count = input('购买个数>>: ').strip()
    if not count.isdigit():
        continue
    goods_l.append((choice, msg_dic[choice], count))

    print(goods_l)

 六、字典

#作用:存多个值,key-value存取,取值速度快
#定义:key必须是不可变类型,value可以是任意类型

info={'name':'egon','age':18,'sex':'male'}   #本质是info=dict({})

info=dict(name='dingding', age=18, sex='male')

info=dict([['name','egon'],('age',18)])
或
{}.fromkeys(('name','age','sex'),None)


# 优先掌握的操作:
# 1.按key存取值:可存可取
# 2.长度len
# 3.成员运算in 和 not in
# 4.删除
# 5.键keys(), 值values(), 键值对items()
# 6.循环

练习

1 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中

即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

a = {'k1': [], 'k2': []}
c = [11,22,33,44,55,66,77,88,99,90]

for i in c:
    if i > 66:
        a['k1'].append(i)
    else:
        a['k2'].append(i)
print(a)

作业

# 作业一:三级菜单
# 要求:
# 打印省市县三级菜单
# 可返回上一级
# 可随时退出程序
menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'老男孩':{},
'北航':{},
},
'天通苑':{},
'回龙观':{},
},
'朝阳':{},
'东城':{},
},
'上海':{
'闵行':{
"人民广场":{
'炸鸡店':{}
}
},
'闸北':{
'火车战':{
'携程':{}
}
},
'浦东':{},
},
'山东':{},
}

# 要求:
# 打印省、市、县三级菜单
# 可返回上一级
# 可随时退出程序

tag = True
while tag:
menu_1 = menu
for key in menu_1: # 打印第一层
print(key)
choice1 = input('第一层>>: ').strip() # 选择第一层

if choice1 == 'b': # 输入b, 则返回上一级
break
if choice1 == 'q': # 输入q, 则退出整体
tag = False
continue
if choice1 not in menu_1: # 输入内容不再menu1内,则继续输入
continue

while tag:
menu_2 = menu_1[choice1] # 拿到choice1对应的一层字典
for key in menu_2:
print(key)

choice2 = input('第二层>>: ').strip()
if choice2 == 'b': # 输入b, 则返回上一级
break
if choice2 == 'q': # 输入q, 则退出整体
tag = False
continue
if choice2 not in menu_2: # 输入内容不再menu1内,则继续输入
continue

while tag:
menu_3 = menu_2[choice2]
for key in menu_3:
print(key)

choice3 = input('第三层>>: ').strip()
if choice3 == 'b': # 输入b, 则返回上一级
break
if choice3 == 'q': # 输入q, 则退出整体
tag = False
continue
if choice3 not in menu_3: # 输入内容不再menu1内,则继续输入
continue

while tag:
menu_4 = menu_3[choice3]
for key in menu_4:
print(key)

choice4 = input('第四层>>: ').strip()
if choice4 == 'b': # 输入b, 则返回上一级
break
if choice4 == 'q': # 输入q, 则退出整体
tag = False
continue
if choice4 not in menu_4: # 输入内容不再menu1内,则继续输入
continue
### 改进版
layers = [menu]
while True:
if len(layers) == 0:
break
current_layer = layers[-1]
print(current_layer)
for key in current_layer:
print(key)
choice = input('>>: ').strip()

if choice == 'b':
layers.pop(-1)
continue
if choice == 'q':
break
if choice not in current_layer:
continue
layers.append(current_layer[choice])
 

 

posted on 2019-06-02 19:49  丁祖平  阅读(317)  评论(0编辑  收藏  举报