📜  Python示例中的基本数据类型指南

📅  最后修改于: 2020-07-31 11:26:45             🧑  作者: Mango

Python数据类型简介

在本文中,我们将深入探讨Python中基本数据类型。这些构成了您可以表示数据的一些基本方式。

对这些基本数据类型进行分类的一种方法是四组之一:

  • 数字intfloat以及不常见到complex
  • 序列:(str字符串)listtuple
  • 布尔值:(TrueFalse)
  • 字典:(dict字典)数据类型,由(key, value)对组成

重要的是要指出,Python通常不需要您指定要使用的数据类型,而是根据变量的含义将数据类型分配给变量。

需要指出的同等重要的一点是,Python是一种“松散/弱类型”编程语言,这意味着变量可以在程序执行过程中更改其类型,而“强类型”编程语言则不是这种情况。 (例如Java或C++)。

因此,如果为它分配一个字符串值,那么int最终可以str很容易地实现。

在我们的示例中,我们偶尔会使用一个称为的函数type(variable),该函数返回返回给我们的变量的类型。

我们还将使用Python shell,因此我们没有繁琐的代码来打印我们想要显示的所有内容。

数值数据类型

这些数据类型非常简单,代表数值。这些可以是十进制值,浮点值,甚至可以是复数。

整数数据类型-int

int数据类型与整型值的交易。这意味着像0、1,-2和-15之类的值,而不是像0.5、1.01,-10.8等之类的数字。

如果将以下代码提供给Python,它将得出a一个整数,并为其分配int数据类型:

>>> x = 5
>>> type(x)

我们本可以更具体一些,并按照这些思路讲一些话,以确保Python将我们理解5为整数,但是,它会自动在幕后做同样的事情:

>>> x = int(5)
>>> type(x)

值得注意的是,Python将任何数字序列(不带前缀)都视为十进制数。实际上,此顺序不受限制。

也就是说,与Java等其他语言不同,的值int没有最大值-它是无界的。

sys.maxsize然后,这可能听起来违反直觉,因为它暗示那是整数的最大值,但事实并非如此。

>>> x = sys.maxsize
>>> x
2147483647

不过,这似乎是一个32位带符号的二进制整数值,让我们看看如果给分配一个更大的数字会发生什么x

>>> x = sys.maxsize
>>> x+1
2147483648

实际上,我们甚至可以做到:

>>> y = sys.maxsize + sys.maxsize
>>> y
4294967294

整数最大的唯一实际限制是运行Python的计算机的内存。

前缀整数

如果您想以其他形式打包数值,会发生什么?您可以给数字序列加上前缀,并告诉Python在不同的系统中对待它们。

更具体地说,前缀:

  • 0b0B-将整数转换为二进制
  • 0o0O-将整数转换为八进制
  • 0x0X-将整数转换为十六进制

因此,让我们尝试一下:

# Decimal value of 5
>>> x = 5
>>> x
5

# Binary value of 1
>>> x = 0b001
>>> x
1

# Octal value of 5
>>> x = 0o5
>>> x
5

# Hexadecimal value of 10
>>> x = 0x10
>>> x

浮点数据类型-浮点

float数据类型可以表示浮点数,多达15位小数。这意味着它可以覆盖数字,例如0.3,-2.8、5.542315467等,但也可以覆盖整数。

点后超过15个数字的数字将被截断。例如,Python毫无困难地正确理解以下内容float

>>> y = 2.3
>>> type(y)

>>> y = 5/4
>>> type(y)

但是,如前所述,如果我们仅说5Python将其视为int数据类型。如果由于某种原因,我们想要一个float具有value 的变量5,我们需要显式让Python知道:

>>> y = 5.0
>>> type(y)

>>> y = float(5)
>>> type(y)

此数据类型可用于表示一些特殊的“数字”,例如NaN(“非数字”),+ /-无限大和指数:

>>> y = float('-infinity')
>>> y
-inf
>>> y = float(5e-3)
>>> y
0.005
>>> y = float('nan')
>>> y
nan

这里一个有趣的旁注是NaN行为方式。即,运行y == float('nan')将返回False,即使y不是数字。

实际上,通过比较值和引用可以将其行为视为奇怪:

>>> x = float('nan')
>>> x == float('nan')
False
>>> x == x
False
>>> x is x
True

当然发生这种情况是因为NaN本来是要这样操作的,但这仍然很有趣。

 

复数-复数

我们需要介绍的最后一个数字类型是complex类型。它是一种很少使用的数据类型,其作用是在复杂的对中表示虚数。

该字符j用于表示数字的虚部,这与i数学中常用的字符不同。

这是因为Python遵循电气工程实践,而不是为复数的虚部命名的数学实践。

让我们看看如何在Python中声明复数: 

# Assigning a value of 0r and 1j to `com`
>>> com = 1j

# Printing `com`s value
>>> com
1j

# Multiplying complex numbers
>>> com*com
(-1+0j)

# Assigning a value to a new `com` number
>>> com2 = 3 + 1j

# Adding two complex numbers
>>> com+com2
(3+2j)

# Assigning a new value to `com`
>>> com = complex(1 + 2j)

# Printing `com`
>>> com
(1+2j)

序列数据类型

序列数据类型用于表示某种类型的集合。这些元素集合可以由相同类型或完全不同类型的元素组成。

力量

字符串是字符序列,用单引号或双引号表示。这包括空字符串(引号之间没有任何字符)。

与整数类似,字符串实际上没有设置硬长度限制。从技术上讲,只要您的计算机内存允许,您就可以创建字符串。

字符串非常常见,因为它们是表示字符序列或单词的最基本方法:

>>> my_string = 'some sequence of characters'
>>> my_string
'some sequence of characters'
>>> type(my_string)

它们也可以包含特殊值,其中一些是\n如果我们希望字符串在打印时换行,或者想要使用特殊字符如 \'或者"需要在它们之前添加反斜杠,例如\

在它们之前添加反斜杠会导致对特殊字符进行转义,因为我们不希望考虑其特殊含义-我们希望使用其文字值。

>>> my_string = "adding a new line \n and some double quotes \" to the string"
>>> print(my_string)
adding a new line 
 and some double quotes " to the string

另一种不用担心在每一个'或之前添加反斜杠的方法"是改为使用'''(三引号),Python会在我们需要的任何地方添加反斜杠:

>>> my_string = '''No need to worry about any ' or " we might have'''
>>> my_string
'No need to worry about any \' or " we might have'

我们可以在将a转换float为a的同时演示Python的“弱类型”性质str

# Assigning float value to `z`
>>> z = 5.2

# Checking for the type of `z`
>>> type(z)


# Printing the value of `z`
>>> z
5.2

# Changing `z` into a string
>>> z = str(z)

# Checking the type of `z`
>>> type(z)


# Printing the value of `z`
>>> z
'5.2'

我们可以看到z它的类型更改没有太大问题。

List

与字符串不同,列表可以包含任何数据类型的有序序列,甚至可以包含同一列表中的多个不同数据类型。

它们是通过在之间提供列表的元素来创建的[],例如,[element1, element2]或者通过[]稍后简单地编写并添加元素来创建它们。

除其他方法外,还有一些内置方法可用于反转,排序,清除,扩展列表,以及追加(末尾插入),在特定位置插入或删除元素等。

元素可以通过列表中的索引进行访问,索引的起始位置为0

为了查看名为的列表的列表的第一个元素(如果不为空)some_list,可以使用,some_list[0]并且对列表的所有其他元素也是如此。

这些元素也可以i通过编写在索引处更改some_list[i] = new_value

让我们列出一个清单并对其执行一些操作:

# Making an empty list
>>> some_list = []

# Printing the value of the list
>>> some_list
[]

# Checking the type of the list
>>> type(some_list)


# Appending an integer to the list
>>> some_list.append(5)

# Printing the value of the list
>>> some_list
[5]

# Inserting an element at the `0`th index
>>> some_list.insert(0, 'some string')

# Printing the value of the list
>>> some_list
['some string', 5]

# Printing the value of the element on the `1`st index
>>> some_list[1]
5

# Appending another element ot the list
>>> some_list.append(123)

# Printing the value of the list
>>> some_list
['some string', 5, 123]

# Assigning the second element, an already existing value, to a new value
>>> some_list[2] = 'a'

# Printing the value of the list
>>> some_list
['some string', 5, 'a']

但是,如果您尝试对类型不匹配的列表进行排序:

>>> some_list.sort()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: '<' not supported between instances of 'int' and 'str'

由于int无法将a str<运算符进行比较-会引发错误。不过,如果我们有:

>>> some_list = [1, 6, 4, 2, 8, 7]
>>> some_list
[1, 6, 4, 2, 8, 7]
>>> some_list.sort()
>>> some_list
[1, 2, 4, 6, 7, 8]

我们可以对它进行排序。

元组Tuple

tuple数据类型是非常相似的名单,唯一的区别是,它是不可变的,并且它的使用产生()替代[]。这意味着,一旦创建了tuple,就无法更改其包含的值。

在大多数情况下,它们比列表快一些,用于保护数据不被更改: 

# Creating a tuple
>>> some_tuple = ("some string", 5, True, float('nan'))

# Printing the value of a tuple
>>> some_tuple
('some string', 5, True, nan)

# Accessing an element of a tuple
>>> some_tuple[0]
'some string'

# Accessing elements from given index to the end of the tuple
>>> some_tuple[1:]
(5, True, nan)

# Accessing elements from given index to another given index
>>> some_tuple[1:3]
(5, True)

# Trying to assign a new value to the element at the `0`th index
>>> some_tuple[0] = 'some other string' # Causes an error

布尔类型-布尔

bool数据类型被用来表示布尔值- TrueFalse。数据类型不能包含任何其他值。

但是,Python仍然可以将大多数内容转换为bool。也就是说,如果您碰巧说bool(5),Python会考虑True,而bool(0)会考虑False

基本上,0是错误的,1是真实的。超出范围的任何内容1也将被处理True。字符串也发生类似的情况,如果您分配一个空字符串,则将其视为False

booleanification(也称为感实性在Python)是在Python的期望一个任何上下文隐式进行bool价值。例如,“说if(5)“与的效果相同if(bool(5)),即if(True)

让我们看看如何声明和使用布尔值:

# Declaring a boolean
>>> some_bool = True

# Printing a boolean's value
>>> some_bool
True

# Checking a boolean's type
>>> type(some_bool)


# Assigning an empty string to a boolean
>>> some_bool = bool('')

# Checking the boolean's value
>>> some_bool
False

请注意,TrueFalse是关键字,您不能说truefalse

>>> some_bool = false
# Throws an error

字典类型-dict

与数据类型的“序列”组不同,dicts(字典)是无序集合。具体来说,是(key, value)对的无序集合。这意味着,与列表不同的是,值与键关联,而不与整数索引关联。

字典具有以下结构:

{
	key1 : value1,
	key2 : value2,
	....
	keyN : valueN
}

重要的是要注意,键必须唯一,而值则必须唯一。当您想查找一个值时,可以传入它的键并检索该对。

可以通过以下方式创建字典:在两者(key, value)之间添加对{}(请记住,[]用于列表和()用于元组),或者干脆写一个空{}并稍后添加对。

键和值可以具有不同的数据类型:

# Checking the value of a dict
>>> type({})


# Assigning keys and values to a dict
>>> some_dict = { 5 : 'five', 4 : 'four'}

# Printing the value of a dict
>>> some_dict
{5: 'five', 4: 'four'}

# Accessing a dict element via its key
>>> some_dict[5]
'five'

# Assigning a new value to a key
>>> some_dict[6] = 'six'

# Printing the value of the dict
>>> some_dict
{5: 'five', 4: 'four', 6: 'six'}

# Removing the (key, value) pair that has the key 5 (this also returns the value)
>>> some_dict.pop(5) 
'five'

# Trying to access an element with the key 5
>>> some_dict[5] # Raises an error since the key 5 no longer exists

结论

Python的编写方式使代码尽可能易于编写,而又不会使代码过于模棱两可。

但是,它的易于编写,弱类型的性质可能会在其他人查看您的代码或在编写代码后重新访问它时引起混乱。最好在任何可能出现歧义的地方写出应该是什么类型的确切类型,并避免重复使用具有不同类型的变量名。