python 的 数据类型

 数据类型

1.1整型int

py2中有int有范围,超出自动转为long长整型,py3中只有int

整除py2中无小数,可加一行代码实现

十进制转二进制
print(bin(10)
十进制转八进制
print(oct(10))
十进制转十六进制
print(hex(10))

 

1.2布尔值bool

只有True和False.

0, '' , [] , {} , () , set() , None都可转化为False,其他为True.

1.3字符串

字符串
x='abcdef字'
    x[0:3:2]   #取字符串元素: ac
    len(x)     #字符串取长:7
    x.strip()  #去空格和特殊字符
l='get|a.txt|333'.split('|')  #['get', 'a.txt', '333']
l_new='|'.join(l)             # get|a.txt|333
​
​
#依赖索引
    for i in range(0,len(x)):   #  abcdef字
        print(x[i],end='')
​
    i=0
    while i < len(x):
        print(x[i])
        i+=1
​
​
#不依赖索引
    for item in x:
        print(item)
​
#格式化字符串
    'my name is %s' %('egon',)      # my name is egon
    'my name is {} {} {}'.format('a','b','c')       # my name is a b c
    'my name is {0} {1} {1}'.format('a','b','c')    # my name is a b b
    'my name is {x} {y} {z}'.format(z='aaaa',y='bbb',x='ccccc')     # my name is aaaa bbb ccccc
View Code
方法含义备注
.lower() 小写  
.upper() 大写  
.strip() 去空格 lstrip()去左侧空格,rstrip()去右侧空格
.split() 分割 split('x'),用切割成一个列表,rsplit从右切割
.isdigit() 判断是否是数字  
.capitalize() 首字母大写 其余小写
.count() 计数 计算()的内容出现次数
.encode() 编码 (encoding='')''里为编码类型
.endswith() 以...结尾 ()里为内容
.startswith() 以...开头 ()里为内容
.find() 查找 ()里为内容,找不到返回-1
.format() 格式化输出 '{0}',fomat()
.join() 加入 '_'.join('abc') a_b_c
.replace() 替换 replace(a,b)把a换成b

1.4列表

#列表

goods=['mac','apple','iphone','tesla']
goods.remove('apple') #
goods.pop(-1) #返回 tesla, pop删除指定元素,并返回原删除元素
方法含义备注
append() 追加  
insert() 插入 (0,a)第0个索引位置插入a
clear() 清空  
extend() 延长 把()的内容挨个追加到列表
pop() 删除 删除索引项,返回删除的值
remove() 删除 删除值,无值报错
reverse() 反转  
sort() 排序 默认升序,(reverse=True)降序

1.5字典

1 用途:以key:value的形式存多个值 优点:存取都快,每一个值都有对应的key

2 定义方式:{ }内以逗号分隔多个元素,格式为key:value,其中key必须为不可变类型,value可以是任意类型

dic=dict(x=1,y=2,z=3) # {'x': 1, 'y': 2, 'z': 3}
print(dic)

dic={'name':'egon'}    # 添加字典元素
dic['age']=10
print(dic)    # {'name': 'egon', 'age': 10}

list1=['name','age','sex'] # 使用for循环添加 同一个 字典元素
dic={}
for x in list1:
dic[x]=None
print(dic)/
print({}.fromkeys(['name','age','sex'],None)) #使用.fromkeys添加 同一个 字典元素 {'name': None, 'age': None, 'sex': None}


dic['name']='EGON'    # 修改字典元素
print(dic)    #{'name': 'EGON', 'age': 10}

dic={'name':'egon','age':18}
print(len(dic))    # 求字典长度 2
dic['name']=dic['name'].upper()    #.upper 取字典大写value

#删除
dic={'name':'egon','age':18}    # pop()可返回被删除的value:egon
res=dic.pop('name')    # del (dic['name']) del只能执行删除命令,无返回值
print(res)    # pop('sex',none) 无关键字 返回none,不会报错

dic={'name':'egon','age':18}    
print(dic.keys())    # dict_keys(['name', 'age'])
print(dic.values())    # dict_values(['egon', 18])
print(dic.items())    # dict_items([('name', 'egon'), ('age', 18)])

for x in dic.keys():    # name
print(x)    # age     
for item in dic.items():    #('name', 'egon')
print(item)    #('age', 18)
for k in egon:    # name egon
print(k,egon[k])    # age 18

#转列表    
print(list(dic.keys()))    # ['name', 'age']
print(list(dic.keys())[0])    # name

for k, v in dic.items(): 
print(k,v)    # name egon
# age 18
#取字典元素
dic={'name':'egon','age':18}
print(dic.get("ddsddddddddddddd"))    # .get取字典中没有的元素时,返回None
print(dic[ddddddddddddddddddd])    # 报错
#更新
dic={'name':'egon','age':18}    #{'name': 'egon', 'age': 19, 'x': 1}
dic.update({'x':1,'age':19})    # 更新,没有则添加,有则覆盖
print(dic)
View Code

1.51字典总结

1、存多个值 2、无序 3、可变

方法含义备注
clear() 清空  
get() 取对应键的值 get(key)=value
items() 取所有键值对 伪列表
keys() 取所有键 伪列表
values() 取所有值 伪列表
pop() 删除  
update() 更新 a.update(b)把b的内容更新到a

1.52销售商品问题

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
goods=[]
​
while True:
    for name in msg_dic:
        print('商品名:%s   价钱:%s' %(name,msg_dic[name]))
​
    good_name=input('商品名>>: ').strip()
    if good_name not in msg_dic:
        continue
    price=msg_dic[good_name]
​
​
    while True:
        count=input('购买个数>>: ').strip()
        if count.isdigit():
            count=int(count)
            break################################################
​
    info={
        'good_name':good_name,
        'price':price,
        'count':count
    }
​
    goods.append(info)
    print(goods ,'总价:%s' %(count*price))
View Code

1.6元组

什么是元组:“元组就是一个不可变的列表”,把[ ]改成( )

1 用途:存多个值,但是只有读的需求,没有改的需求

强调:在元素个数相同的情况下,使用元组更加节省空间

2 定义方式 t=(1,2,3,4) # t=tuple((1,2,3,4))

3
3 常用操作+内置的方法
    优先掌握的操作:
    1、按索引取值(正向取+反向取):只能取
    t=(1,2,3,4,5,6)         
    print(t[1:4])           # (2, 3, 4)
    
    2、依赖索引,依次取值      
    t=(1,2,'a')             # 1
    i=0                    # 2
    while i < len(t):       # a
        print(t[i])
        i+=1////for i in range(len(t)):
        print(t[i])
        
    3 不依赖索引,依次取值    # 1
    for item in t:          # 2
        print(item)         # a
                           
    4、切片(顾头不顾尾,步长)
    5、长度
    6、成员运算in和not in
    7、循环
    8、索引和计数
    t=('a','b','c','c')
    print(t.index('a')) # 0
    print(t.count('c')) # 2

1.61元组总结

1 存多个值 2 有序 3 不可变

1.7集合

定义方式:在{ }内用逗号分隔开一个个元素 注意的问题 1、集合内没有重复的元素 2、集合的元素必须是不可变类型,但set集合是可变

用途 1、 关系运算 2、去重

s1=set('hello')         # 转集合 {'e', 'h', 'o', 'l'}
print(s1)
​
l=['a','b',1,'a','a']    # 去重 ['b', 'a', 1]
print(list(set(l)))
​
                        #去重且保留原顺序(了解)
l = ['a', 'b', 1, 'a', 'a']
l_new=[]
s=set()
​
for item in l:
    if item not in s:
        s.add(item)          #s={'a','b',1}
        l_new.append(item)    #l_new=['a','b',1]
#关系运算:        
stus_linux={'alex','egon','张全蛋','李铁蛋','oldboy'}
stus_python={'李二丫','wxx','liudehua','alex','egon'}
​
交集
print(stus_linux & stus_python)
print(stus_linux.intersection(stus_python))
​
并集
print(stus_linux | stus_python)
print(stus_linux.union(stus_python))
#for循环实现求交集
stus_py_lx=[]
for stu in stus_linux:
    if stu in stus_python:
        stus_py_lx.append(stu)
 print(stus_py_lx)
​
差集
print(stus_linux - stus_python)
print(stus_linux.difference(stus_python))
​
交叉补集
print(stus_linux ^ stus_python)
print(stus_linux.symmetric_difference(stus_python))
​
查看                           #1
s1={1,'a','b','c','d'}          #d  
for item in s1:                 #a  
    print(item)                 #c
                               #b
            
增加
s1={'a','b','c'}         # 一次添加一个值
s1.add('d')             #{'b', 'c', 'a', 'd'}
print(s1)          
          
s1={'a','b','c'}        #一次添加多个值
s1.update({3,4,5})      # {'a', 'c', 3, 4, 5, 'b'}
print(s1)
​
删除
s1={'a','b','c'}         ## 当删除的元素不存在的时候,不会报错
s1.discard(4)           #{'c', 'a', 'b'}
print(s1)
​
s1.remove(4)            # 当删除的元素不存在的时候,报错
print(s1)
​
s1={'a','b','c'}         #随机取走一个元素
res=s1.pop()             # a
print(res)
View Code
方法含义备注
.add() 添加  
clear() 清空  
difference() 差集 a.difference(b)=a-b
discard() 删除  
union() 合集 a.union(b)=a+b
intersection() 交集  
symmetric_difference() 对称差集  
update() 更新  

1.8可变与不可变类型

可变类型不可变类型
列表 数字
字典 字符串
集合 元组

 

原文地址:https://www.cnblogs.com/mylu/p/10973884.html