python学习(1)-数据类型整理

本文介绍了Python3中的六种标准数据类型:Number、String、List、Tuple、Sets和Dictionary,强调了可变和不可变数据类型的区别,并提供了各种操作示例,包括字符串操作、列表操作、字典操作、元组、文件处理、数字转换和集合操作。还提到了模块的使用,如random、decimal和Fraction。
摘要由CSDN通过智能技术生成

最近发现一个比较好的python学习网站:python网站

Python3 基本数据类型

标准数据类型

Python3 中有六个标准的数据类型:

  • Number(数字)
  • String(字符串)
  • List(列表)      
  • Tuple(元组)
  • Sets(集合)
  • Dictionary(字典)

Python3 的六个标准数据类型中:

  • 不可变数据(四个):Number(数字)、String(字符串)、Tuple(元组)、Sets(集合);
  • 可变数据(两个):List(列表)、Dictionary(字典)

列表和字典是可变数据类型,他们的添加或删除在原处进行,因此共享引用时需要特别小心

#列表
a=[1,2,3]
b=a
b.append(4)
print("a=",a)
print("b=",b)
#字典
c={'name':'JK'}
d=c
d['age']=24
print("c=",c)
print("d=",d)

输出:

a= [1, 2, 3, 4]
b= [1, 2, 3, 4]
c= {'name': 'JK', 'age': 24}
d= {'name': 'JK', 'age': 24}

参考博客:python3基本数据类型

列表:

变量[头下标:尾下标]  
例如 list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ]

元组:

tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2  )

集合:

student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}

    集合可进行逻辑、加减运算

字典:

dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])
输出:{'Taobao': 3, 'Runoob': 1, 'Google': 2}
 {x: x**2 for x in (2, 4, 6)}
输出:{2: 4, 4: 16, 6: 36}
dict(Runoob=1, Google=2, Taobao=3) 
输出:{'Taobao': 3, 'Runoob': 1, 'Google': 2}

字符串操作函数

字符串本身不可改变,但可以重新赋值

str="Spam"
print(str.upper())
print(str)#字符串不变
print(str.replace('a','A'))

str="aaa,bbb,ccc"
print(str.split(','))

str="你好"
str1="hello"
str2="111"
str3="11hello"
print("function s.isalpha() test\n")
print("%s is %d" % (str,str.isalpha()))
print("%s is %d" % (str1,str1.isalpha()))
print("%s is %d" % (str2,str2.isalpha()))
print("%s is %d" % (str3,str3.isalpha()))

输出:

SPAM
Spam
SpAm
['aaa', 'bbb', 'ccc']
function s.isalpha() test

你好 is 1
hello is 1
111 is 0
11hello is 0

查询ASCII:

ord('A')

#输出
65

字符串模式匹配:

import re #用到了re模块
match=re.match('Hello (.*) world','Hello python world')
print("the match word : %s" %(match.groups()))#输出全部
print(match.group(0))#序列0 为匹配字符
print(match.group(1))#序列1 为匹配得到的字符

path='/(.*)/(.*)/(.*)/(.*)'
real_path='/user/home/jk/Desktop'
match=re.match(path,real_path)
print(match.groups())
print(match.group(0))#序列0 输出groups
print(match.group(1))#序列1 输出groups的第一个部分

输出:

the match word : python
Hello python world
python
('user', 'home', 'jk', 'Desktop')
/user/home/jk/Desktop
user

字符串格式化 .format()

举例:

a='{} is a {}'.format('Jack','student')
print(a)

列表操作函数:

列表可直接扩充,扩充函数l.append()

l=['aaa','bbb','ccc']
l.append('ddd')
print(l)

#回顾
str='aaa,bbb,ccc'
list=str.split(',')
print("str is %s\nlist is "%(str),end='')
print(list)

输出:

['aaa', 'bbb', 'ccc', 'ddd']
str is aaa,bbb,ccc
list is ['aaa', 'bbb', 'ccc']

删除列表对应数据l.pop()

列表排序l.sort()

列表倒叙输出l.reverse()

#删除列表数据
l=[1,2,3,4,5]
print(l)
print("delete list[1]")
l.pop(1)
print(l)
print()#换行
#列表排序
l=[2,5,7,3,22,11,0,-4]
print(l)
l.sort()
print(l)
#列表翻转,翻转本身是不排序的!,需要结合sort
l.reverse()
print(l)

输出:

[1, 2, 3, 4, 5]
delete list[1]
[1, 3, 4, 5]

[2, 5, 7, 3, 22, 11, 0, -4]
l.sort
[-4, 0, 2, 3, 5, 7, 11, 22]
[22, 11, 7, 5, 3, 2, 0, -4]

列表嵌套和解析

l=[1,2,3],[3,4,5],[4,5,6]
print("l is",l,"\nl[1][2] is ",l[1][2])
#取第一列
l1=[row[1] for row in l]#并非必须是row,也可以是其他,row只是命名刚好如此
print("l1 is ",l1)
#取第一行
c1=[col[1] for col in l]#错误的做法
print("col[1] is ",c1)
c1=[l[1]]
print("col[1] is ",c1)

输出:

l is ([1, 2, 3], [3, 4, 5], [4, 5, 6]) 
l[1][2] is  5
l1 is  [2, 4, 5]
col[1] is  [2, 4, 5]
col[1] is  [[3, 4, 5]]

字典

字典和列表一样也是可变的,不同的是,列表通过l.append()函数扩展,字典直接添加:

D={}
D['name']='Jim'
D['job']='student'
D['age']=20
print(D)
print(D['name'])

输出:

{'name': 'Jim', 'job': 'student', 'age': 20}
Jim

字典的排序:

字典本身不是一个序列,因此不存在顺序,因此只能考虑对其键的排序使字典可以有序

D={}
D['name']='Jim'
D['job']='student'
D['age']=20
print(D)
D_Keys=list(D.keys())
D_Keys.sort()
for key in D_Keys:
    print(key,' : ',D[key],end=',')

输出:

{'name': 'Jim', 'job': 'student', 'age': 20}
age  :  20,job  :  student,name  :  Jim,

元组

T=(1,2,3,4)
print(T.count(2))#2的出现次数
print(T.index(2))#数字2的编号
输出:
1
1

文件

path='/home/jk/Desktop'
file=path+'/data.txt'
#写数据
print(file)
f=open(file,'w')
f.write("hello world\n")
f.write("hello world\n")
f.close()
#读文件
f=open(file)
text=f.read()
print(text)

输出:

/home/jk/Desktop/data.txt
hello world
hello world

数字:

数字的强制转换:

十六进制:0x

八进制:0o

二进制:0b

使用hex(),oct(),bin(),int(*,*)强制转换

num=10
#十进制转十六进制
h=hex(num)
print(h)
#十进制转八进制
o=oct(num)
print(o)
#十进制转二进制
b=bin(num)
print(b)
#二进制转八进制
o=oct(int(b,2))#先强制转化十进制
print(o)

输出:

0xa
0o12
0b1010
0o12

其他:

int(),float()强制转换类型函数

%4.2f   float类型,总长度四位,小数两位,不足四位的空格补齐

真除法,传统出发,floor除法

python3.0:

真除法: 不论除数与被除数类型,返回值都是浮点型

10/4=2.5   4/2=2.0

Floor除法:忽略计算结果的小数部分,返回值却不一定是整形(向下舍入)

10//4=2   10//4.0=2.0   -5//2=-3

python3 不存在传统除法

集合

集合是唯一.不可变对象的一个无序集合

x=set('abcde')
print("x=",x)#x= {'d', 'a', 'e', 'b', 'c'}
if 'a' in x:
    print("a is in x")#a is in x
#集合的逻辑操作
y=set('af')
print("y=",y)           #y= {'a', 'f'}
print("x-y=",(x-y))     #x-y= {'d', 'e', 'b', 'c'}
print("x|y=",(x|y))     #x|y= {'d', 'e', 'b', 'a', 'f', 'c'}
print("x&y=",(x&y))     #x&y= {'a'}
#异或,不一样的留下,一样的删去
print("x^y",(x^y))      #x^y {'e', 'd', 'c', 'f', 'b'}

z=x.intersection(y)     #等同于x&y
print(z)                #{'a'}
z.update(set(['x','y']))
print(z)                 #{'x', 'y', 'a'}
z.add('g')
print(z)                #{'x', 'g', 'y', 'a'}



模块使用

random

import random
print(random.random())
print(random.randint(1,9))
print(random.randrange(1.0,9.0))

输出:

0.5819219362548528
6
4

decimal

设置小数精度

import decimal
print(decimal.Decimal(1)/decimal.Decimal(7))#0.1428571428571428571428571429
#设置临时精度
with decimal.localcontext() as temp:
    temp.prec=2
    print(decimal.Decimal(1) / decimal.Decimal(7))#0.14
    temp.prec=3
    print(decimal.Decimal(1) / decimal.Decimal(7))##0.143

#设置全局精度
decimal.getcontext().prec=4
print(decimal.Decimal(1)/decimal.Decimal(7))#0.1429
#计算浮点数
print(0.1 + 0.1 + 0.1 - 0.1 - 0.2)#2.7755575615628914e-17
print(decimal.Decimal(str(0.1))+decimal.Decimal(str(0.1))-decimal.Decimal(str(0.2)))#0.0

Fraction

import  fractions
#浮点 转化为 分数比例
a=2.5
b=a.as_integer_ratio()
print(b)
print(b[0],b[1])
#浮点 转化为 分数
z=fractions.Fraction(a)
print(z)


#浮点 转化为 分数
c=fractions.Fraction.from_float(a)
print(c)
(5, 2)
5 2
5/2
5/2








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值