百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python基础篇-数据类型(python数据类型8种)

off999 2024-10-31 13:58 25 浏览 0 评论

目录

一、 数据类型介绍

二、 简单结构

三、 多维结构

·【列表】、元组、集合、字典

·列表、【元组】、集合、字典

·列表、元组、【集合】、字典

·列表、元组、集合、【字典】


一、数据类型介绍

Python中的数据类型主要包括:

1.整数(int):表示整数,例如:x = 2。

2.浮点数(float):表示带有小数点的数值,例如:y = 1.23。

3.布尔值(bool):表示真(True)或假(False)的值,用于逻辑运算,例如:is_true = True。

4.字符串(str):表示文本数据,可以使用单引号或双引号表示,例如:text = "Welcome, Python!"。

5.列表(list):有序的可变容器,可以包含不同数据类型的元素,例如:colorlist = [99, 88, 'red']。

6.元组(tuple):有序的不可变容器,例如:my_tuple = (3, 2, 'orange')。

7.集合(set):无序的可变容器,不允许重复元素,例如:my_set = {1, 2, 3}。

8.字典(dict):无序的键值对集合,例如:my_dict = {'name': 'Jay', 'age': 35}。

9.复数(complex):包含实部和虚部的数值,例如:z = 4 + 4j。

10.字节串(bytes):以字节为单位的不可变序列,例如:b = b'python'。

11.字节数组(bytearray):以字节为单位的可变序列,例如:ba = bytearray(b'python')。


简单结构:整数、浮点数、布尔值、字符串

多维结构:列表、元组、集合、字典

其他类型特定情况下才使用到,暂不介绍。

二、简单结构

使用一个简单例子介绍,有一个学生姓名为Judy,年龄是22,成绩是89.5,判断是否大于90分可以根据此构建四个变量模型age/score/boolScore/name(格式:整数/浮点数/布尔值/字符串),并进行格式化输出,同步输出变量模型对应格式,如代码所示。

# 整数
age = 22
# 浮点数
score = 89.5
# 布尔值 分数是否大于等于90
boolScore = True if score >= 90 else False
# 字符串
name = "Judy"

print(f"age:{age},score:{score},boolScore:{boolScore},name:{name}")
print(f"age:{type(age)},score:{type(score)},boolScore:{type(boolScore)},name:{type(name)}")

>>>runfile('C:/xxx/learnvar.py',wdir='C:/xxx/learn')
age:22,score:89.5,boolScore:False,name:Judy
age:<class 'int'>,score:<class 'float'>,boolScore:<class 'bool'>,name:<class 'str'>

三、多维结构

·【列表】、元组、集合、字典

# --------------------------------------------

# 列表(list):有序的可变容器,可以包含不同数据类型的元素

# type(colorslist) <class 'list'>

# --------------------------------------------

列表基本操作,索引访问列表

>numbers = [1,2,3,4]
>print(numbers[1],numbers[0:2],numbers[0:],"Bob" in numbers)
2 [1, 2] [1, 2, 3, 4] False

列表迭代,比如输出偶数

for number in numbers:
if number % 2 == 0:
print(number) # 返回 2 4

列表修改

>colors = ['red','yellow','green','blue']
>print(colors)
>colors[0] = "burgundy" # 索引修改
>colors[1:3] = ["orange","magenta"] # 切片赋值
>print(colors)
>colors[1:3] = ["orange","magenta","aqua"]
>print(colors)
['red', 'yellow', 'green', 'blue']
['burgundy', 'orange', 'magenta', 'blue']
['burgundy', 'orange', 'magenta', 'aqua', 'blue']

列表增加list.insert

>colors = ['red','yellow','green','blue']
>print(colors)
>colors.insert(1,"orange") # 在索引1位置插入
>print(colors)
>colors.insert(10,"violet") # 超过索引位置插入,直接插到末尾
>print(colors)
>colors.insert(-1,"indigo") # 插入倒数第一个
>print(colors)
['red', 'yellow', 'green', 'blue']
['red', 'orange', 'yellow', 'green', 'blue']
['red', 'orange', 'yellow', 'green', 'blue', 'violet']
['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

列表删除list.pop,append末尾增加

>colors.pop(3)
>print(colors)
>colors.pop(-1) # 负值索引
>print(colors)
>colors.pop() # 删除最后一个
>print(colors)
>colors.append("indigo")
>print(colors)
['red', 'orange', 'yellow', 'blue', 'indigo', 'violet']
['red', 'orange', 'yellow', 'blue', 'indigo']
['red', 'orange', 'yellow', 'blue']
['red', 'orange', 'yellow', 'blue', 'indigo']

列表统计

>nums = [1,2,3,4,5]
>print(sum(nums),max(nums),min(nums))

列表扩展列表推导式

>numbers = (1,2,3,4,5)
>squares = [num**2 for num in numbers]
>print(numbers,squares)
15 5 1
(1, 2, 3, 4, 5) [1, 4, 9, 16, 25]

·列表、【元组】、集合、字典

# --------------------------------------------

# 元组(tuple):有序的不可变容器

# type(first_tuple) <class 'tuple'>

# --------------------------------------------

元组定义和输出,类型,长度,切片访问

>first_tuple = (1,2,3)
>print(first_tuple,type(first_tuple),len(first_tuple),first_tuple[0],first_tuple[0:3])
(1, 2, 3) <class 'tuple'> 3 1 (1, 2, 3)

元组遍历,迭代

> for item in first_tuple:
> print(item*2) # 返回 2 4 6

元组 打包解包 = 两端元素数量相等,批量赋值

coordinates = 5.21,8.29
x,y = coordinates
a,b,c,d = 1,2,3,4

元组使用in检查是否包含某值

coo = tuple('coordinates')
print("o" in coo) # True
print("a" in coo) # True
print("z" in coo) # False

·列表、元组、【集合】、字典

# --------------------------------------------

# 集合(set):无序的可变容器,不允许重复元素

# type(s) <class 'set'>

# --------------------------------------------

集合创建一个集合

>s = {1, 2, 3, 4, 5}
>print(s)
{1, 2, 3, 4, 5}

集合添加元素

>s.add(6)
>print(s)
{1, 2, 3, 4, 5, 6}

集合移除元素

>s.remove(3)
>print(s)
{1, 2, 4, 5, 6}

集合的并集操作

>s1 = {3, 4, 5}
>unions = s | s1
>print(s,s1,unions)
{1, 2, 4, 5, 6} {3, 4, 5} {1, 2, 3, 4, 5, 6}

集合的交集操作

>intersections = s & s1
>print(s,s1,intersections)
{1, 2, 4, 5, 6} {3, 4, 5} {4, 5}

集合的差操作

>differences = s - s1
>print(s,s1,differences)
{1, 2, 4, 5, 6} {3, 4, 5} {1, 2, 6}

集合的对称差操作(异或运算)

>symmetric_differences = s ^ s1
>print(s,s1,symmetric_differences)
{1, 2, 4, 5, 6} {3, 4, 5} {1, 2, 3, 6}

集合的成员检查

>print(2 in s) # 返回 True

集合的长度

>print(len(s),len(s1)) # 返回5,3

集合的遍历

for item in s1:
print(item) # 返回 3 4 5

·列表、元组、集合、【字典】

# --------------------------------------------

# 字典(dict):无序的键值对集合,列表不能作为字典的键

# type(capitals) <class 'dict'>

# --------------------------------------------

字典 创建字典

>capitals = {
> "California":"Sacramento",
> "New York":"Albany",
> "Texas":"Austin",
>}
>print(capitals)
{'California': 'Sacramento', 'New York': 'Albany', 'Texas': 'Austin'}

字典增加

>capitals["Colorado"] = "Denver"
>print(capitals)
{'California': 'Sacramento', 'New York': 'Albany', 'Texas': 'Austin', 'Colorado': 'Denver'}

字典修改

>capitals["Texas"] = "Houston"
>print(capitals)
{'California': 'Sacramento', 'New York': 'Albany', 'Texas': 'Houston', 'Colorado': 'Denver'}

字典删除

>del capitals["Texas"]
>print(capitals)
{'California': 'Sacramento', 'New York': 'Albany', 'Colorado': 'Denver'}

字典键判断

>print("Arizona" in capitals,"California" in capitals)
False True

字典通过key,value,items()访问读取

>for key in capitals:
> print(key)
California
New York
Colorado

>for state in capitals:
> print(f"The capital of {state} is {capitals[state]}")
The capital of California is Sacramento
The capital of New York is Albany
The capital of Colorado is Denver

>for state,capital in capitals.items():
> print(f"The capital of {state} is {capital}")
The capital of California is Sacramento
The capital of New York is Albany
The capital of Colorado is Denver


下篇预告:python基础篇-函数

相关推荐

让 Python 代码飙升330倍:从入门到精通的四种性能优化实践

花下猫语:性能优化是每个程序员的必修课,但你是否想过,除了更换算法,还有哪些“大招”?这篇文章堪称典范,它将一个普通的函数,通过四套组合拳,硬生生把性能提升了330倍!作者不仅展示了“术”,更传授...

7 段不到 50 行的 Python 脚本,解决 7 个真实麻烦:代码、场景与可复制

“本文整理自开发者AbdurRahman在Stackademic的真实记录,所有代码均经过最小化删减,确保在50行内即可运行。每段脚本都对应一个日常场景,拿来即用,无需额外依赖。一、在朋...

Python3.14:终于摆脱了GIL的限制

前言Python中最遭人诟病的设计之一就是GIL。GIL(全局解释器锁)是CPython的一个互斥锁,确保任何时刻只有一个线程可以执行Python字节码,这样可以避免多个线程同时操作内部数据结...

Python Web开发实战:3小时从零搭建个人博客

一、为什么选Python做Web开发?Python在Web领域的优势很突出:o开发快:Django、Flask这些框架把常用功能都封装好了,不用重复写代码,能快速把想法变成能用的产品o需求多:行业...

图解Python编程:从入门到精通系列教程(附全套速查表)

引言本系列教程展开讲解Python编程语言,Python是一门开源免费、通用型的脚本编程语言,它上手简单,功能强大,它也是互联网最热门的编程语言之一。Python生态丰富,库(模块)极其丰富,这使...

Python 并发编程实战:从基础到实战应用

并发编程是提升Python程序效率的关键技能,尤其在处理多任务场景时作用显著。本文将系统介绍Python中主流的并发实现方式,帮助你根据场景选择最优方案。一、多线程编程(threading)核...

吴恩达亲自授课,适合初学者的Python编程课程上线

吴恩达教授开新课了,还是亲自授课!今天,人工智能著名学者、斯坦福大学教授吴恩达在社交平台X上发帖介绍了一门新课程——AIPythonforBeginners,旨在从头开始讲授Python...

Python GUI 编程:tkinter 初学者入门指南——Ttk 小部件

在本文中,将介绍Tkinter.ttk主题小部件,是常规Tkinter小部件的升级版本。Tkinter有两种小部件:经典小部件、主题小部件。Tkinter于1991年推出了经典小部件,...

Python turtle模块编程实践教程

一、模块概述与核心概念1.1turtle模块简介定义:turtle是Python标准库中的2D绘图模块,基于Logo语言的海龟绘图理念实现。核心原理:坐标系系统:原点(0,0)位于画布中心X轴:向右...

Python 中的asyncio 编程入门示例-1

Python的asyncio库是用于编写并发代码的,它使用async/await语法。它为编写异步程序提供了基础,通过非阻塞调用高效处理I/O密集型操作,适用于涉及网络连接、文件I/O...

30天学会Python,开启编程新世界

在当今这个数字化无处不在的时代,Python凭借其精炼的语法架构、卓越的性能以及多元化的应用领域,稳坐编程语言排行榜的前列。无论是投身于数据分析、人工智能的探索,还是Web开发的构建,亦或是自动化办公...

Python基础知识(IO编程)

1.文件读写读写文件是Python语言最常见的IO操作。通过数据盘读写文件的功能都是由操作系统提供的,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个...

Python零基础到精通,这8个入门技巧让你少走弯路,7天速通编程!

Python学习就像玩积木,从最基础的块开始,一步步搭建出复杂的作品。我记得刚开始学Python时也是一头雾水,走了不少弯路。现在回头看,其实掌握几个核心概念,就能快速入门这门编程语言。来聊聊怎么用最...

一文带你了解Python Socket 编程

大家好,我是皮皮。前言Socket又称为套接字,它是所有网络通信的基础。网络通信其实就是进程间的通信,Socket主要是使用IP地址,协议,端口号来标识一个进程。端口号的范围为0~65535(用户端口...

Python-面向对象编程入门

面向对象编程是一种非常流行的编程范式(programmingparadigm),所谓编程范式就是程序设计的方法论,简单的说就是程序员对程序的认知和理解以及他们编写代码的方式。类和对象面向对象编程:把...

取消回复欢迎 发表评论: