首页 技术 正文
技术 2022年11月21日
0 收藏 523 点赞 4,445 浏览 1801 个字

I. 数据类型

Python3将程序中的任何内容统称为对象(Object),基本的数据类型有数字和字符串等,也可以使用自定义的类(Classes)创建新的类型。

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

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

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

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

1. Number:int, float, bool, complex

a, b, c, d = 1, 2.3, True, 4+5j
print(type(a), type(b), type(c), type(d), type(a+b+c+d), a+b+c+d)

<class ‘int’> <class ‘float’> <class ‘bool’> <class ‘complex’> <class ‘complex’> (8.3+5j)

2. String:

Python中的字符串用单引号’或双引号”括起来,同时使用反斜杠\转义特殊字符。r或R表示原始字符串。

s = r’this is raw string \n \t.’
print(type(s), s)

<class ‘str’> this is raw string \n \t.

3. List:

列表是写在方括号[]之间,用逗号分隔开的元素列表。列表的元素可以是数字、字符串和列表。

4. Tuple:

元组是写在小括号()之间,用逗号分隔开的元素列表。

t = (1, 2.3, True, 4+5j, (6, ‘abc’, [‘d’, {‘id’: 9, ‘value’: ‘dict’}]))
print(type(t), t)

<class ‘tuple’> (1, 2.3, True, (4+5j), (6, ‘abc’, [‘d’, {‘id’: 9, ‘value’: ‘dict’}]))

5. Set:

集合可以使用{}或set()函数来创建,创建空集合必须用set()。

基本功能是测试成员关系和删除重复元素。

s1 = {1.2, 4+5j, ‘abc’, ‘abc’, ‘d’}
s2 = set(‘abcdde’)
print(type(s1), s1, type(s2), s2)
print(s1 – s2, s1 | s2, s1 & s2, s1 ^ s2)

<class ‘set’> {1.2, (4+5j), ‘d’, ‘abc’} <class ‘set’> {‘c’, ‘a’, ‘d’, ‘e’, ‘b’}
{1.2, (4+5j), ‘abc’} {1.2, ‘c’, ‘a’, ‘d’, (4+5j), ‘abc’, ‘e’, ‘b’} {‘d’} {‘c’, 1.2, ‘a’, (4+5j), ‘abc’, ‘e’, ‘b’}

6. Dictionary:

字典通过{}或dict()函数创建,是无序的key:value映射的集合。key必须为不可变类型且唯一。

d1 = {1: ‘abc’, ‘name’: {‘cn’: ‘Chinese name’, ‘en’: ‘English name’}, (True, 4+5j): [1, ‘abc’]}
d2 = dict([(1, ‘abc’), (‘name’, {‘cn’: ‘Chinese name’, ‘en’: ‘English name’})])
d3 = dict(name={‘cn’: ‘Chinese name’, ‘en’: ‘English name’}, one=’abc’)
print(type(d1), d1, d1[(True, 4+5j)])
print(type(d2), d2, d2[1])
print(type(d3), d3, d3[‘one’])

<class ‘dict’> {1: ‘abc’, ‘name’: {‘cn’: ‘Chinese name’, ‘en’: ‘English name’}, (True, (4+5j)): [1, ‘abc’]} [1, ‘abc’]
<class ‘dict’> {1: ‘abc’, ‘name’: {‘cn’: ‘Chinese name’, ‘en’: ‘English name’}} abc
<class ‘dict’> {‘name’: {‘cn’: ‘Chinese name’, ‘en’: ‘English name’}, ‘one’: ‘abc’} abc

II.数据类型转换

Python3数据类型及转换

参考:简明Python教程(英文原版)、菜鸟教程

数据类型转换字符串转字典

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,955
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774