Python 基本数据类型
Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。
在 Python 中,变量就是变量,它没有类型,我们所说的「类型」是变量所指的内存中对象的类型。
Python 中有 2 个与对象类型有关的函数,他们分别是 type()
和 isinstance()
,使用 help()
查看他们的使用方法,截取如下信息:
type(object) -> the object's type
isinstance(obj, class_or_tuple, /)
Return whether an object is an instance of a class or of a subclass thereof.
一、Number
- Python 中支持 int,float,bool,complex.
var1 = 19
var2 = 3.14
var3 = True
var4 = 4+3j
print(type(var1), type(var2), type(var3), type(var4), sep='\n')# 分别是int,float,bool,complex
print(isinstance(var3, bool))
print(isinstance(var3,int))# bool是int的子类
- 算术运算
print(2/4)# 0.5
print(2//4)# 0
print(2**4)# 16
二、String
-
其索引从左到右从 0 开始,从右到左从 -1 开始。
str = '123456789' print(str[0])# 输出str的第1个字符 print(str[-1])# 输出str的倒数第1个字符
-
使用
:
可以连续输出字符串中的字符,甚至可以指定步长。PS. 前包后不包。print(str[:3])# 输出str第1至第3个字符 print(str[::])# 完整输出str print(str[::2])# 输出str中偶数位的字符(步长为2) print(str[-1::-1])# 逆序输出
-
str * n
表示重复输出 n 次 str。print(str * 2)# 输出2次str
-
r + str
可以消除转义符的转义意。print("hello,world\n你好,世界") print(r"hello,world\n你好,世界")
三、List
和 Java 中的集合 List 一样,Python 中的 List 支持多种类型对象的存储。
-
简单的 List 对象
list = ["rosie", 20, 3.14, 4+3j] print(list);
-
索引和切片
print(list[0]) print(list[-1]) print(list[1:4]) print(list[-1::-1])
-
加号和星号
print(list + ["VehnSX", 26]) print(list * 2)
-
元素可变性
list[0] = "VehnSX" print(list)4.
四、Tuple
和 List 一样,Tuple 支持不同类型对象的存储,而其最大的特点就是不可变性。
-
创建存储若干数据的 Tuple 对象。
tuple1 = ("rosie", 20, 3.14, True, 3+4j) print(tuple1)
-
创建存储为空的 Tuple 对象。
tuple2 = () print(tuple2)
-
创建存储一个数据的 Tuple 对象。
tuple4 = ("rosie",)# 注意一定要在后面加上逗号 tuple5 = ("rosie") print(type(tuple4), type(tuple5))# tuple和string
-
验证不可变性。
tuple1 = ("rosie", 20, 3.14, True, 3+4j) tuple1[1]="VehnSX"# 编译出错
五、Set
Set 的基本功能是测试成员关系和删除重复元素。
和 List、Tuple 不一样,Set 是无序的。
-
创建 Set 对象
set1 = {"Google", "Twitter", "Mate"} set2 = set()# 创建空Set只能使用构造器,如果使用空{},则创建的是Dictionary类型对象
-
删除重复元素
set3 = {"Google", "Twitter", "Mate", "Google", "Mate"} print(set3)
-
测试成员关系
if "Google" in set1: print("Yes") else: print("No")
-
还可以进行集合运算
a = set('abcdefg') b = set("iloveyou") print(a-b, a|b, a^b, a&b, sep='\n')# 差集、并集、交集、不同时存在的元素集合
六、Dictionary
相当于 Java 中的 Map,key: value
。
需要注意的是,Python 中 Dictionary 的 Key 值必须唯一,必须使用不可变类型(Number、String、Tuple)。
-
创建 Dictionary 对象
# 创建方式1 dict1 = {} dict1["name"] = "rose" dict1["age"] = 21 print(dict1) # 创建方式2 dict2 = {"name":"jack", "age":"20"} print(dict2) # 创建方式3 dict3 = dict([("name","michael"),("age",22),("gender",0)]) print(dict3)
-
keys()
和values()
print(dict3.keys(), dict3.values(), sep='\n')