原文: https://www.programiz.com/python-programming/variables-datatypes
在本教程中,您将学习可在 Python 中使用的不同数据类型。
Python 中的数据类型
Python 中的每个值都有一个数据类型。 由于在 Python 编程中一切都是对象,因此数据类型实际上是类,而变量是这些类的实例(对象)。
Python 中有多种数据类型。 下面列出了一些重要的类型。
Python 数字
整数,浮点数和复数属于 Python 数字类别。 在 Python 中,它们被定义为int,float和complex类。
我们可以使用type()函数来了解变量或值属于哪个类。 同样,isinstance()函数用于检查对象是否属于特定类。
a = 5print(a, "is of type", type(a))a = 2.0print(a, "is of type", type(a))a = 1+2jprint(a, "is complex number?", isinstance(1+2j,complex))
输出
5 is of type <class 'int'>2.0 is of type <class 'float'>(1+2j) is complex number? True
整数可以是任意长度,仅受可用内存的限制。
浮点数最多可精确到 15 个小数位。 整数和浮点由小数点分隔。 1 是整数, 1.0 是浮点数。
复数以x + yj的形式编写,其中x是实数部分,y是虚数部分。 这里有些例子。
>>> a = 1234567890123456789>>> a1234567890123456789>>> b = 0.1234567890123456789>>> b0.12345678901234568>>> c = 1+2j>>> c(1+2j)
请注意,float变量b被截断了。
Python 列表
列表是项目的有序序列。 它是 Python 中最常用的数据类型之一,非常灵活。 列表中的所有项目都不必是同一类型。
声明列表非常简单。 用逗号分隔的项目括在方括号[ ]中。
a = [1, 2.2, 'python']
我们可以使用切片运算符[ ]从列表中提取一个项目或一系列项目。 索引在 Python 中从 0 开始。
a = [5,10,15,20,25,30,35,40]# a[2] = 15print("a[2] = ", a[2])# a[0:3] = [5, 10, 15]print("a[0:3] = ", a[0:3])# a[5:] = [30, 35, 40]print("a[5:] = ", a[5:])
输出:
a[2] = 15a[0:3] = [5, 10, 15]a[5:] = [30, 35, 40]
列表是可变的,也就是说,列表元素的值可以更改。
a = [1, 2, 3]a[2] = 4print(a)
输出:
[1, 2, 4]
Python 元组
元组是与列表相同的项的有序序列。 唯一的区别是元组是不可变的。 元组一旦创建就无法修改。
元组用于写保护数据,通常比列表快,因为它们不能动态更改。
它在括号()中定义,其中各项之间用逗号分隔。
t = (5,'program', 1+3j)
我们可以使用切片运算符[]提取项目,但不能更改其值。
t = (5,'program', 1+3j)# t[1] = 'program'print("t[1] = ", t[1])# t[0:3] = (5, 'program', (1+3j))print("t[0:3] = ", t[0:3])# Generates error# Tuples are immutablet[0] = 10
输出:
t[1] = programt[0:3] = (5, 'program', (1+3j))Traceback (most recent call last):File "test.py", line 11, in <module>t[0] = 10TypeError: 'tuple' object does not support item assignment
Python 字符串
字符串是 Unicode 字符序列。 我们可以使用单引号或双引号来表示字符串。 可以使用三引号'''或"""表示多行字符串。
s = "This is a string"print(s)s = '''A multilinestring'''print(s)
输出:
This is a stringA multilinestring
就像列表和元组一样,切片运算符[ ]可以与字符串一起使用。 但是,字符串是不可变的。
s = 'Hello world!'# s[4] = 'o'print("s[4] = ", s[4])# s[6:11] = 'world'print("s[6:11] = ", s[6:11])# Generates error# Strings are immutable in Pythons[5] ='d'
输出:
s[4] = os[6:11] = worldTraceback (most recent call last):File "<string>", line 11, in <module>TypeError: 'str' object does not support item assignment
Python 集
集是唯一项的无序集合。 集由用大括号{ }内的逗号分隔的值定义。 集合中的项目不排序。
a = {5,2,3,1,4}# printing set variableprint("a = ", a)# data type of variable aprint(type(a))
输出:
a = {1, 2, 3, 4, 5}<class 'set'>
我们可以在两个集合上执行集合操作,例如联合,相交。 集具有唯一值。 他们消除重复。
a = {1,2,2,3,3,3}print(a)
输出:
{1, 2, 3}
由于集是无序集合,因此索引没有意义。 因此,切片运算符[]不起作用。
>>> a = {1,2,3}>>> a[1]Traceback (most recent call last):File "<string>", line 301, in runcodeFile "<interactive input>", line 1, in <module>TypeError: 'set' object does not support indexing
Python 字典
字典是键值对的无序集合。
当我们拥有大量数据时,通常使用它。 字典针对检索数据进行了优化。 我们必须知道检索值的键。
在 Python 中,字典在花括号{}中定义,每一项都是一对,形式为key:value。 键和值可以是任何类型。
>>> d = {1:'value','key':2}>>> type(d)<class 'dict'>
我们使用键来检索相应的值。 但并非相反。
d = {1:'value','key':2}print(type(d))print("d[1] = ", d[1]);print("d['key'] = ", d['key']);# Generates errorprint("d[2] = ", d[2]);
输出:
<class 'dict'>d[1] = valued['key'] = 2Traceback (most recent call last):File "<string>", line 9, in <module>KeyError: 2
数据类型之间的转换
我们可以使用int(),float(),str()等不同的类型转换函数在不同的数据类型之间进行转换。
>>> float(5)5.0
从float到int的转换将截断该值(使其接近零)。
>>> int(10.6)10>>> int(-10.6)-10
字符串之间的转换必须包含兼容的值。
>>> float('2.5')2.5>>> str(25)'25'>>> int('1p')Traceback (most recent call last):File "<string>", line 301, in runcodeFile "<interactive input>", line 1, in <module>ValueError: invalid literal for int() with base 10: '1p'
我们甚至可以将一个序列转换为另一序列。
>>> set([1,2,3]){1, 2, 3}>>> tuple({5,6,7})(5, 6, 7)>>> list('hello')['h', 'e', 'l', 'l', 'o']
要转换为字典,每个元素必须成对:
>>> dict([[1,2],[3,4]]){1: 2, 3: 4}>>> dict([(3,26),(4,44)]){3: 26, 4: 44}
