Python基础之数据类型

Python基础之数据类型

本节会介绍Python中最基本的内置数据类型,包括数值类型和非数值类型。


数据类型分类

数值类型:整型(int),浮点型(float),布尔类型(bool),复数类型(complex

非数值类型:字符串(str),列表(list),元组(tuple),字典(dict

要点

  • Python中定义一个变量不用指定类型,直接赋值即可
  • 数值类型可以相互计算,不用类型转换
  • 内置函数type()可用于查看某个变量的类型
  • 布尔类型有两个值,TrueFalse,在Python内部,如果布尔类型用于计算,True看做 1,False看做 0
  • 一般情况不用考虑数值类型占用的字节数,Python内部会自动处理

示例:

# No need to specify variable type
num = 10

# All digital data type can calculate each other
print(num + 2.5 + True)
print(num - 2.5 + False)
print(num * 2.5 + True)
print(num / 2.5 + False)
a = 1 + 2j
print(num * a)

# Use print method to show data type
print(type(1))
print(type(1.1))
print(type(True))
print(type(1+2j))
print(type('hello'))
print(type([1,2,3]))
print(type((1,2,3)))
print(type({'name':'xiaoming', 'age':20}))

输出:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_01/common.py
13.5
7.5
26.0
4.0
(10+20j)
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'complex'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>

Process finished with exit code 0

类型转换

格式说明
int(x)将x转换为int类型
float(x)将x转换为float类型
bool(x)将x转换为bool类型,如果x为0,则转换后为False,否则为True
complex(x)将x转换为complex类型
str(x)将x转换为str类型
list(x)将x转换为list类型。很方便拆分字符串为每个字符。
tuple(x)将x转换为tuple类型。很方便拆分字符串为每个字符。
dict将x转换为dict类型。可将一个嵌套的列表转换为dict。

列表

列表中可存放不同类型的数据,但推荐存放相同的类型,便于处理。

定义:

my_list = []

my_list = [1, 2, 3, 4, 'a', 'b', True, False]

操作:

操作函数说明
增加增加元素:append 方法my_list.append(data)
在指定位置增加元素:insert 方法my_list.insert(index, data)
增加一个列表: extend 方法my_list.extend(list2)
删除删除某个index的数据,del 函数 或 del 关键字del(my_list[index]), del my_list[index]
删除某个index的数据:pop 方法my_list.pop(index), my_list.pop()
删除某个list中的所有元素 clear 方法my_list.clear()
修改修改某个index的值:[]my_list[index] = new data
查找获取某个index的值: []a = Fmy_list[index]
统计长度 len() 函数len(my_list)
某个元素出现的次数 count 方法my_list.count(data)
排序sort 方法

my_list.sort() # 升序

my_list.sort(reverse=True) # 降序

reverse 方法逆序my_list.reverst()

示例:

my_list = [2, 4, 5, 1, 3, 8, 10]
print(my_list)

# Append 12
my_list.append(12)
print(my_list)

# Append 7
my_list.append(7)
print(my_list)

# Insert 22 at index 2
my_list.insert(2, 22)
print(my_list)

# Delete the last data
my_list.pop()
print(my_list)

# Delete the data which index is 2
my_list.pop(2)
print(my_list)

# Delete the data which index is 1
del(my_list[1])
print(my_list)

# Assign a new data to the first element
my_list[0] = 0
print(my_list)

# Get the first element
print(my_list[1])

# The length of my_list
print(len(my_list))

# The max value of my_list
print(max(my_list))

# The min value of my_list
print(min(my_list))

# The count of elements which value is 10
print(my_list.count(10))

# Sort
my_list.sort()
print(my_list)

# Reverse sort
my_list.sort(reverse=True)
print(my_list)

# Reverse the my_list
my_list.reverse()
print(my_list)

# Clean my_list
my_list.clear()
print(my_list)

输出:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_01/list_operations.py
[2, 4, 5, 1, 3, 8, 10]
[2, 4, 5, 1, 3, 8, 10, 12]
[2, 4, 5, 1, 3, 8, 10, 12, 7]
[2, 4, 22, 5, 1, 3, 8, 10, 12, 7]
[2, 4, 22, 5, 1, 3, 8, 10, 12]
[2, 4, 5, 1, 3, 8, 10, 12]
[2, 5, 1, 3, 8, 10, 12]
[0, 5, 1, 3, 8, 10, 12]
5
7
12
0
1
[0, 1, 3, 5, 8, 10, 12]
[12, 10, 8, 5, 3, 1, 0]
[0, 1, 3, 5, 8, 10, 12]
[]

Process finished with exit code 0

元组

元组和列表类似,都存放某些数据,可以是相同类型,也可以是不同类型。与列表最大的不同是元组中的数据不可修改。

定义:

t = ()

t = (1, 2, 3, 4, 'a', 'b')

操作:

两个方法和一个函数:

t.count(data) : data出现的次数

t.index(data) : data出现的index

len(t) : t 的长度

元组的使用场景:

  1. 函数的参数和返回值,参数是不定个数,返回值是返回多个数据
  2. 格式化字符串
  3. 保护列表不被修改

字典

字典中存放的是key-value的数据,无序,键唯一,值任意。键只能是字符串数字元组等不可变类型的数据类型,一般情况用字符串。

定义:

m = {'name':'xiaoming', 'age':22}

操作:

操作函数说明
增加 k-v[]m['sex'] = 'M'
取值[]print(m['sex'])
删除pop 方法m.pop('sex'), 删除sex 这个键
修改[]m['age'] = 30
长度len 函数len(m),m中键值对个数
合并update 方法

m.update(m2)

清空clear 方法m.clear()

注:在for...in...循环遍历中,是对key进行遍历

示例:

m = {'name': 'xiaoming', 'age': 20}
print(m)

m['sex'] = 'M'
print(m)

m.pop('sex')
print(m)

m['age'] = 30
print(m)

print(len(m))

for k in m:
    print('%s -> %s' % (k, m[k]))

输出:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_01/map_operations.py
{'name': 'xiaoming', 'age': 20}
{'name': 'xiaoming', 'age': 20, 'sex': 'M'}
{'name': 'xiaoming', 'age': 20}
{'name': 'xiaoming', 'age': 30}
2
name -> xiaoming
age -> 30

Process finished with exit code 0

字符串

定义:

s = "This is a testing string"

s = 'This is another string'

操作:

操作说明
len(s)计算s的长度
s.count('abc')统计 abc 出现的次数
s.index('abc')

abc 中出现的index。如果没有找到则报错。

s.startswith('abc')

判断s是否以abc开始

s.endswith('abc')判断s是否以abc结尾
s.find(str, start=...)查找str,与index类似,但如果不存在不会报错
s.replace(old, new, num)字符串替换,默认全部替换
s.strip()去掉s两边的空白字符
s.split(str='abc', num)按abc来split字符串s
s.splitlines()

按行来拆分字符串,分行

‘abc’.join(list)拼接字符串,按 abc 来拼接list中的元素

示例:

s = "This is a testing string"
print(len(s))

print(s.count('s'))

print(s.index("t"))

print(s.startswith("This"))

print(s.startswith("TThis"))

print(s.endswith("string"))

print(s.endswith("stringG"))

print(s.find("testing"))

print(s.replace('testing', 'test'))

print(s)

s2 = '  This is a testing string  '
print(s2)
print(s2.strip())

s2_list = s2.split(' ')
print(s2_list)

print('#'.join(s2_list))

输出:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_01/str_operations.py
24
4
10
True
False
True
False
10
This is a test string
This is a testing string
  This is a testing string  
This is a testing string
['', '', 'This', 'is', 'a', 'testing', 'string', '', '']
##This#is#a#testing#string##

Process finished with exit code 0

切片

对list,tuple,str可以做切片操作,以获取部分长度的数据。

格式:

s[begin_index : end_index : steps]

  • begin_index 如果不指定,默认是 0
  • end_index 如果不指定,默认是 len(s)
  • 整个切片长度:end_index - begin_index。注:需要都大于0的正常情况。
  • steps如果不指定,默认是1
  • 如果begin_index为 -1,则表示最后一个元素
  • steps如果为 -1,表示从后往前遍历

示例:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l[2: 5])
print(l[2: 9: 2])
print(l[: 9: 2])
print(l[4:: 2])
print(l[::-1])
print(l[::-2])
print(l[-2::-2])

t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(t[2: 5])
print(t[2: 9: 2])
print(t[: 9: 2])
print(t[4:: 2])
print(t[::-1])
print(t[::-2])
print(t[-2::-2])

s = "abcdefghijklmnopqrstuvwxyz"
print(s[2: 5])
print(s[2: 9: 2])
print(s[: 9: 2])
print(s[4:: 2])
print(s[::-1])
print(s[::-2])
print(s[-2::-2])

输出:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_01/slice_operations.py
[2, 3, 4]
[2, 4, 6, 8]
[0, 2, 4, 6, 8]
[4, 6, 8]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 7, 5, 3, 1]
[8, 6, 4, 2, 0]
(2, 3, 4)
(2, 4, 6, 8)
(0, 2, 4, 6, 8)
(4, 6, 8)
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
(9, 7, 5, 3, 1)
(8, 6, 4, 2, 0)
cde
cegi
acegi
egikmoqsuwy
zyxwvutsrqponmlkjihgfedcba
zxvtrpnljhfdb
ywusqomkigeca

Process finished with exit code 0

遍历

对list,tuple,str,dict等可以使用for...in..进行遍历,以访问每个元素,

格式:

for ... in ...:
    pass

示例:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in l:
    print(i, end=" ")

print()
t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
for i in t:
    print(i, end=" ")

print()
s = "abcdefghijklmnopqrstuvwxyz"
for i in s:
    print(i, end=" ")

print()
m = {'name': 'xiaoming', 'age': 20}
for k in m:
    print('%s -> %s' % (k, m[k]))

输出:

D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_01/for_in.py
0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 
a b c d e f g h i j k l m n o p q r s t u v w x y z 
name -> xiaoming
age -> 20

Process finished with exit code 0

非数值类型公共运算

运算符说明适用类型
+连接,合并list,tuple,str
*重复list,tuple,str
in元素是否存在list,tuple,str,dict
not in元素是否不存在list,tuple,str,dict
>, >=, <, <=, ==比较元素list,tuple,str

len()

计算长度list,tuple,str,dict
del()删除元素list,tuple,str,dict
max()最大元素list,tuple,str,dict
min()最小元素list,tuple,str,dict

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值