什么是标准的数据类型?
变量可以包含不同类型的值。例如,一个人的名字必须存储为字符串,而其id必须存储为整数。
Python提供了各种标准数据类型,用于定义每个数据类型的存储方法。Python中定义的数据类型:数字、字符串、列表、元组、字典。
数字Number
数字存储数值。当数字分配给变量时,Python会创建Number对象。例如;a = 3 ,b = 5 #a,b是数字对象
Python支持4种类型的Number数据。int(有符号整数,如10,2,29等)
long(长整数用于更高范围的值,如908090800L,-0x1929292L等)
float(float用于存储浮点数,如1.9,9.902,15.2等)
complex(复杂的数字,如2.14j,2.0 + 2.3j等)
Python允许我们使用小写L来使用长整数。但是,我们必须始终使用大写L来避免混淆。
复数包含有序对,即x + iy,其中x和y分别表示实部和虚部。
字符串String
字符串可以定义为引号中表示的字符序列。在python中,我们可以使用单引号,双引号或三引号来定义字符串。
python中的字符串处理是一项简单的任务,因为提供了各种内置函数和运算符。
在字符串处理的情况下,operator +用于连接两个字符串,因为操作“hello”+“python”返回“hello python”。
operator *被称为重复运算符,因为操作“Python”* 2返回“Python Python”。
以下示例说明了python中的字符串处理。str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
输出:he
o
hello javatpointhello javatpoint
hello javatpoint how are you
列表list
列表类似于C中的数组。但是; 列表可以包含不同类型的数据。存储在列表中的项目用逗号(,)分隔,并用方括号[]括起来。
我们可以使用slice [:]运算符来访问列表的数据。连接运算符(+)和重复运算符(*)以与处理字符串相同的方式使用列表。
如下示例:l = [1, "hi", "python", 2]
print (l[3:]);
print (l[0:2]);
print (l);
print (l + l);
print (l * 3);
输出:[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
元组tuple
元组在很多方面类似于列表。与列表一样,元组也包含不同数据类型的项集合。元组的项用逗号(,)分隔并括在括号()中。
元组是只读数据结构,因为我们无法修改元组项的大小和值。
让我们看一个元组的简单例子。t = ("hi", "python", 2)
print (t[1:]);
print (t[0:1]);
print (t);
print (t + t);
print (t * 3);
print (type(t))
t[2] = "hi";
输出:('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
Traceback (most recent call last):
File "main.py", line 8, in
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
字典dictionary
Dictionary是键值对项的有序集合。它就像一个关联数组或一个哈希表,其中每个键存储一个特定的值。Key可以保存任何原始数据类型,而value是任意Python对象。
字典中的项目用逗号分隔,并用花括号{}括起来。
请考虑以下示例。d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'};
print("1st name is "+d[1]);
print("2nd name is "+ d[4]);
print (d);
print (d.keys());
print (d.values());
输出:1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
[1, 2, 3, 4]
['Jimmy', 'Alex', 'john', 'mike']