当前位置: 首页 > article >正文

Python3入门--数据类型

文章目录

  • 一、基础语法
    • 编码
    • 标识符
    • 注释
      • 单行注释以 # 开头
      • 多行注释用多个 # 号,还有 ''' 和 """
    • 空行
    • 行与缩进
    • 同一行显示多条语句
    • 多行语句
  • 二、数据类型
    • Number(数字)
      • type和isinstance查询变量类型
      • 数值运算
    • String(字符串)
    • bool(布尔)
    • List(列表)
      • 创建列表
      • 访问列表元素
      • 列表切片
      • 修改列表
      • 列表操作
      • 列表方法
      • 列表推导式
    • Tuple(元组)
      • 元组方法
    • Set(集合)
      • 创建集合
      • 遍历集合
      • 判断元素在集合中
      • 判断元素不在集合中
      • 集合推导式
      • 集合方法
    • Dictionary(字典)
      • 创建字典
      • 访问字典元素
      • 添加或修改键值对
      • 删除键值对
      • 遍历字典
      • 字典方法

入门python3,先学习一些基础的语法和数据类型。

一、基础语法

编码

默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。
当然你也可以为源码文件指定不同的编码。

标识符

  • 第一个字符必须是字母表中字母或下划线 _ 。
  • 标识符的其他的部分由字母、数字和下划线组成。
  • 标识符对大小写敏感。

在 Python 3 中,可以用中文作为变量名,非 ASCII 标识符也是允许的了

注释

单行注释以 # 开头

#!/usr/bin/python3
 
# 第一个注释
print ("Hello, Python!") # 第二个注释

多行注释用多个 # 号,还有 ‘’’ 和 “”"

#!/usr/bin/python3
 
# 第一个注释
# 第二个注释
 
'''
第三注释
第四注释
'''
 
"""
第五注释
第六注释
"""
print ("Hello, Python!")

空行

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

行与缩进

python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {}
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。

举个栗子:

if True:
    print ("True")
else:
    print ("False")

缩进不一致可能会导致报错:

if True:
    print ("Answer")
    print ("True")
else:
    print ("Answer")
  print ("False")    # 缩进不一致,会导致运行错误

同一行显示多条语句

Python 可以在同一行中使用多条语句,语句之间使用分号 ;

print("Hello"); print("World");print("Python")
# 三个print语句都会被执行,分别输出 Hello World Python

多行语句

Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠 \ 来实现多行语句。

total = item_one + \
        item_two + \
        item_three

[], {}, 或 () 中的多行语句,不需要使用反斜杠 \

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

二、数据类型

Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。

在 Python 中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象的类型。

等号(=)用来给变量赋值。

多个变量赋值

  • a = b = c = 1 # 输出a b c都是1
  • a, b, c = 1, 2, 3 # 输出a=1 b=2 c=3

Python3 中常见的数据类型有:

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

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

此外还有一些高级的数据类型,如: 字节数组类型(bytes)。


Number(数字)

python中数字有四种类型:整数、布尔型、浮点数和复数。

  • int (整数): 如 1, 只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
  • bool (布尔): 如 True。
  • float (浮点数): 如 1.23、3E-2
  • complex (复数): - 复数由实部和虚部组成,形式为 a + bj,其中 a 是实部,b 是虚部,j 表示虚数单位。如 1 + 2j、 1.1 + 2.2j

type和isinstance查询变量类型

isinstance 和 type 的区别在于:

  • type()不会认为子类是一种父类类型。
  • isinstance()会认为子类是一种父类类型。
a, b, c, d = 10, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))
# <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

print(isinstance(a, int))
# True

注意:Python3 中,boolint 的子类,True 和 False 可以和数字相加, True==1、False==0 会返回 True,但可以通过 is 来判断类型。

# True 和 False 与数字相加
print(True + 5)  # 输出: 6
print(False + 10)  # 输出: 10

# True 和 False 分别等同于 1 和 0
print(True == 1)  # 输出: True
print(False == 0)  # 输出: True

# 使用 is 来判断类型
print(True is 1)  # 输出: False,因为 True 是 bool 类型,而 1 是 int 类型
print(False is 0)  # 输出: False,因为 False 是 bool 类型,而 0 是 int 类型

数值运算

+(加法) -(减法) *(乘法) /(除法,得到浮点数) //(除法,得到整数) %(取余) **(乘方)


String(字符串)

  • 单引号 ' 和双引号 " 使用完全相同。
    single_quotes = 'Hello, world!'
    double_quotes = "Hello, world!"
    print(single_quotes == double_quotes)  # 输出: True
    
  • 使用三引号('''""")可以指定一个多行字符串。
    multi_line = """
    这是一个多行字符串。
    它可以在多行上展开。
    """
    print(multi_line)
    
  • 转义符 \
    new_line = "第一行\n第二行"
    print(new_line)
    
  • 使用r 可以让反斜杠不发生转义
    raw_string = r"this is a line with \n"
    print(raw_string)  # 输出: this is a line with \n
    
  • 按字面意义级联字符串
    concatenated = "this " "is " "string"
    print(concatenated)  # 输出: this is string
    
  • 使用 + 运算符连接字符串,用 * 运算符重复字符串
    join_strings = "Hello, " + "world!"
    print(join_strings)  # 输出: Hello, world!
    
    repeated_string = "abc " * 3
    print(repeated_string)  # 输出: abc abc abc 
    
  • 两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
    index_example = "Python"
    print(index_example[0])  # 从左往右-输出: P
    print(index_example[-1])  # 从右往左-输出: n
    
  • Python 中的字符串不能改变。
    immutable_str = "immutable"
    # immutable_str[0] = "m"  # 这将引发 TypeError
    
  • Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
    char_example = "P"
    print(type(char_example))  # 输出: <class 'str'>
    
  • 字符串切片 str[start:end]
    # 其中 start(包含)是切片开始的索引,end(不包含)是切片结束的索引。
    slice_example = "Slicing"
    print(slice_example[1:5])  # 截取索引1开始到5之前--输出: lici
    
  • 字符串的切片可以加上步长参数 step str[start:end:step]
    slice_step = "StepByStep"
    print(slice_step[0:5:2])  # 输出: SeB
    
    str='0123456789'
    print(str[0:10:2])   # 输出: 02468
    

bool(布尔)

布尔类型即 TrueFalse

# 布尔类型的值和类型
a = True
b = False
print(type(a))  # <class 'bool'>
print(type(b))  # <class 'bool'>

# 布尔类型的整数表现
print(int(True))   # 1
print(int(False))  # 0

# 使用 bool() 函数进行转换
print(bool(0))         # False
print(bool(42))        # True
print(bool(''))        # False
print(bool('Python'))  # True
print(bool([]))        # False
print(bool([1, 2, 3])) # True

# 布尔逻辑运算 and or not
print(True and False)  # False
print(True or False)   # True
print(not True)        # False

# 布尔比较运算
print(5 > 3)  # True
print(2 == 2) # True
print(7 < 4)  # False

# 布尔值在控制流中的应用
if True:
    print("This will always print")
    
if not False:
    print("This will also always print")
    
x = 10
if x:
    print("x is non-zero and thus True in a boolean context")

注意: 在 Python 中,所有非零的数字和非空的字符串、列表、元组等数据类型都被视为 True,只有 0空字符串空列表空元组等被视为 False。因此,在进行布尔类型转换时,需要注意数据类型的真假性。


List(列表)

list(列表)是一种非常灵活的数据类型,用于存储一系列有序的元素。

创建列表

列表是由方括号 [] 包围的元素集合,元素之间用逗号 , 分隔。列表内的元素可以是不同类型的数据。

# 创建一个空列表
empty_list = []

# 创建一个包含多种数据类型的列表
custom_list = [1, 'hello', 3.12, [11, 22], True]

访问列表元素

列表中的每个元素都有一个索引,索引从 0 开始。可以使用索引来访问列表中的元素。

fruits = ['apple', 'banana', 'cherry']

# 访问第一个元素
first_fruit = fruits[0]  # 'apple'

# 访问最后一个元素
last_fruit = fruits[-1]  # 'cherry'

列表切片

切片操作可以获取列表的一部分,生成一个新的列表。

numbers = [0, 1, 2, 3, 4, 5]

# 获取从索引 1 到 4 的元素(不包括索引 4)
subset = numbers[1:4]  # [1, 2, 3]

修改列表

列表是可变的,你可以修改、添加或删除列表中的元素。

# 修改元素
fruits[0] = 'orange'

# 添加元素到列表末尾
fruits.append('mango')

# 插入元素到指定位置
fruits.insert(1, 'grape')

# 删除指定位置的元素
del fruits[2]

# 移除列表中第一个出现的元素
fruits.remove('banana')

# 清空列表
fruits.clear()

列表操作

列表支持多种操作,如拼接、重复、成员检查等。

# 拼接列表 +
combined = fruits + ['kiwi', 'pear']

# 重复列表 *
repeated = [1, 2, 3] * 3  # [1, 2, 3, 1, 2, 3, 1, 2, 3]

# 成员检查
is_in_list = 3 in [1, 2, 3]  # True

列表方法

列表有很多方法,如 len(), max(), min(), append(), extend(), insert(), remove(), pop(), clear(), count(), index(), sort(), reverse(), copy()

my_list = [1, 2, 3, 4, 5]

# 使用 len() 函数获取列表长度
print(len(my_list)) # 输出: 5

# 使用 max() 函数获取列表中的最大值
print(max(my_list)) # 输出: 5

# 使用 min() 函数获取列表中的最小值
print(min(my_list)) # 输出: 1

# 创建一个元组
my_tuple = (1, 2, 3, 4, 5)
# 使用 list() 函数将元组转换为列表
print(list(my_tuple)) # 输出: [1, 2, 3, 4, 5]


# append 添加到列表的末尾
my_list.append(6)
print(my_list)  # 输出: [1, 2, 3, 4, 5, 6]

# extend 添加多个元素到列表的末尾
my_list.extend([7, 8, 9])
print(my_list)  # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 使用 insert 在指定位置插入元素
my_list.insert(0, 0)
print(my_list)  # 输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 使用 remove 移除元素
my_list.remove(0)
print(my_list)  # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 使用 pop 移除并返回元素
last_element = my_list.pop()
print(last_element)  # 输出: 9
print(my_list)       # 输出: [1, 2, 3, 4, 5, 6, 7, 8]

# 使用 sort 排序列表
my_list.sort(reverse=True)
print(my_list)  # 输出: [8, 7, 6, 5, 4, 3, 2, 1]

# 使用 reverse 反转列表
my_list.reverse()
print(my_list)  # 输出: [1, 2, 3, 4, 5, 6, 7, 8]

# 使用 copy 复制列表
new_list = my_list.copy()
print(new_list)  # 输出: [1, 2, 3, 4, 5, 6, 7, 8]

# 使用 count 指定值的出现数量。
new_count = my_list.count(1)
print(new_count) # 输出: 1

列表推导式

列表推导式是一种简洁的方式来创建列表,基于现有的列表或其他迭代器。

# 创建一个包含 0-9 平方的列表
squares = [x**2 for x in range(10)]


Tuple(元组)

元组(tuple)是一种内置的数据类型,用于存储不可变的有序元素集合。元组写在小括号 () 里,元素之间用,隔开,元组可以包含不同类型的元素。

可以像list一样访问元素

tuple = (1, 'abc', True, 4.56, [5, 'ddd'])
print(tuple[1]) # abc
print(tuple[4][1]) # ddd
print(tuple[2:]) # (True, 4.56, [5, 'ddd'])
print(tuple[:-2]) # (1, 'abc', True)
print(tuple * 2) # (1, 'abc', True, 4.56, [5, 'ddd'], 1, 'abc', True, 4.56, [5, 'ddd']) 
print(tuple + (10, 'xyz')) # (1, 'abc', True, 4.56, [5, 'ddd'], 10, 'xyz')
print(len(tuple)) # 5

元组方法

my_tuple = (1, 2, 3, 4, 5)

# 使用 len() 函数获取元组长度
print(len(my_tuple)) # 输出: 5

# 使用 max() 函数获取元组中的最大值
print(max(my_tuple)) # 输出: 5

# 使用 min() 函数获取元组中的最小值
print(min(my_tuple)) # 输出: 1

# 创建一个列表
my_list = [1, 2, 3, 4, 5]
# 使用 tuple() 函数将列表转换为元组
print(tuple(my_list)) # 输出: (1, 2, 3, 4, 5)

构造包含 0 个或 1 个元素的元组比较特殊,所以有一些额外的语法规则:

tup1 = ()    # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号

虽然tuple的元素不可改变,但它可以包含可变的对象,比如list

tup3 = (1, 2, [3, 4, 5])
tup3[2][0] = 'abc'
print(tup3) # (1, 2, ['abc', 4, 5])

Set(集合)

set(集合)是一个无序且元素唯一的内置数据类型。集合通常用于快速地成员检查、消除重复元素和执行数学集合运算(如并集、交集、差集等)。

创建集合

可以使用花括号 {} 或者 set() 函数来创建集合。如果使用花括号{},则必须至少包含一个元素;如果使用 set(),则可以创建空集合

# 使用花括号创建集合
my_set = {1, 2, 3}

# 使用 set() 函数创建集合
another_set = set([4, 5, 6])

# 创建空集合
empty_set = set()

遍历集合

for element in my_set:
    print(element)

判断元素在集合中

# 创建一个集合
my_set = {1, 2, 3, 4, 5}

# 判断元素是否在集合中
is_in_set = 3 in my_set

# 输出结果
print(is_in_set)  # 输出: True

判断元素不在集合中

# 创建一个集合
my_set = {1, 2, 3, 4, 5}

# 判断元素是否在集合中
is_not_in_set = 6 not in my_set

# 输出结果
print(is_not_in_set)  # 输出: True

集合推导式

my_set = {1, 2, 3, 4, 5}

my_set = {x for x in range(10) if x % 2 == 0} # {0, 2, 4, 6, 8}

集合方法

# add(): 向集合中添加一个元素
s = {1, 2, 3}
s.add(4)
print(s)  # 输出: {1, 2, 3, 4}

# clear(): 清空集合
s = {1, 2, 3}
s.clear()
print(s)  # 输出: set()

# copy(): 返回集合的浅拷贝
s = {1, 2, 3}
s_copy = s.copy()
print(s_copy)  # 输出: {1, 2, 3}

# difference(): 返回两个集合的差集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
result = s1.difference(s2)
print(result)  # 输出: {1}

# difference_update(): 删除集合中另一个集合的元素
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s1.difference_update(s2)
print(s1)  # 输出: {1}

# discard(): 删除集合中的一个元素,如果不存在则不操作
s = {1, 2, 3}
s.discard(4)
print(s)  # 输出: {1, 2, 3}

# intersection(): 返回两个集合的交集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
result = s1.intersection(s2)
print(result)  # 输出: {2, 3}

# intersection_update(): 保留集合中另一个集合的元素
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s1.intersection_update(s2)
print(s1)  # 输出: {2, 3}

# isdisjoint(): 检查两个集合是否没有交集
s1 = {1, 2, 3}
s2 = {4, 5, 6}
print(s1.isdisjoint(s2))  # 输出: True

# issubset(): 检查集合是否是另一个集合的子集
s1 = {1, 2, 3}
s2 = {1, 2, 3, 4}
print(s1.issubset(s2))  # 输出: True

# issuperset(): 检查集合是否是另一个集合的父集
s1 = {1, 2, 3, 4}
s2 = {1, 2, 3}
print(s1.issuperset(s2))  # 输出: True

# symmetric_difference(): 返回两个集合的对称差集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
result = s1.symmetric_difference(s2)
print(result)  # 输出: {1, 4}

# symmetric_difference_update(): 更新集合为另一个集合的对称差集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s1.symmetric_difference_update(s2)
print(s1)  # 输出: {1, 4}

# union(): 返回两个集合的并集
s1 = {1, 2, 3}
s2 = {2, 3, 4}
result = s1.union(s2)
print(result)  # 输出: {1, 2, 3, 4}

# update(): 使用一个集合更新另一个集合
s1 = {1, 2, 3}
s2 = {4, 5, 6}
s1.update(s2)
print(s1)  # 输出: {1, 2, 3, 4, 5, 6}

# pop(): 随机删除集合中的一个元素,并返回该元素。
s = {1, 2, 3, 4, 5}
element = s.pop()
print(element)  # 输出: 1
print(s)  # 输出: {2, 3, 4, 5}

# remove()方法删除集合中的指定元素
s = {1, 2, 3, 4, 5}
s.remove(3)
print(s)  # 输出: {1, 2, 4, 5}

# len()方法返回集合中元素的个数
s = {1, 2, 3, 4, 5}
length = len(s)
print(length)  # 输出: 5


Dictionary(字典)

dict(字典)是一种内置的数据类型,用于存储键值对。字典是无序的,这意味着键值对的出现顺序在字典中是不可预测的。

创建字典

可以使用花括号 {} 或者 dict() 函数来创建字典。

# 使用花括号创建字典
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# 使用 dict() 函数创建字典
another_dict = dict([('name', 'Jane'), ('age', 25), ('city', 'Los Angeles')])

# 创建空字典
empty_dict = {}

访问字典元素

使用键来访问字典中的值。

# 访问字典中的值
value = my_dict['name']  # 输出: John

# 如果键不存在,会引发 KeyError
# value = my_dict['unknown_key']  # 输出: KeyError: 'unknown_key'

添加或修改键值对

# 添加键值对
my_dict['job'] = 'Engineer'

# 修改键值对
my_dict['age'] = 31

删除键值对

# 删除键值对
del my_dict['job']

遍历字典

for key, value in my_dict.items():
    print(key, value)

字典方法

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# 使用 len() 计算字典元素个数,即键的总数。
print(len(my_dict)) # 输出: 3

# 使用 str() 输出字典字符串 
print(str(my_dict)) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}

# 使用 type() 返回输入的变量类型,如果变量是字典就返回字典类型。
print(type(my_dict)) # 输出: <class 'dict'>

# clear(): 清空字典
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict.clear()
print(my_dict)  # 输出: {}


# copy(): 返回字典的浅拷贝
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
new_dict = my_dict.copy()
print(new_dict)  # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}


# fromkeys(): 使用给定的键创建一个新字典,每个键的值都是默认值
keys = ['name', 'age', 'city']
value = 'default'
new_dict = dict.fromkeys(keys, value)
print(new_dict)  # 输出: {'name': 'default', 'age': 'default', 'city': 'default'}


# get(): 返回指定键的值,如果键不存在,则返回默认值
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict.get('name'))  # 输出: John
print(my_dict.get('gender'))  # 输出: None


# items(): 返回一个包含字典中所有键值对的视图对象
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
items = my_dict.items()
print(items)  # 输出: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

# keys(): 返回一个包含字典中所有键的视图对象
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
keys = my_dict.keys()
print(keys)  # 输出: dict_keys(['name', 'age', 'city'])


# pop(): 删除指定键的键值对,并返回其值
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
value = my_dict.pop('age')
print(value)  # 输出: 30
print(my_dict)  # 输出: {'name': 'John', 'city': 'New York'}

# popitem(): 删除字典中的最后一对键值对,并返回它
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
value = my_dict.popitem()
print(value)  # 输出: ('city', 'New York')
print(my_dict)  # 输出: {'name': 'John', 'age': 30}


# setdefault(): 如果键不存在于字典中,则设置其值
my_dict = {'name': 'John', 'age': 30}
my_dict.setdefault('city', 'New York')
print(my_dict)  # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}


# update(): 使用另一个字典的键值对更新当前字典
my_dict = {'name': 'John', 'age': 30}
new_dict = {'city': 'New York', 'gender': 'Male'}
my_dict.update(new_dict)
print(my_dict)  # 输出: {'name': 'John', 'age': 30, 'city': 'New York', 'gender': 'Male'}


# values(): 返回一个包含字典中所有值的视图对象
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
values = my_dict.values()
print(values)  # 输出: dict_values(['John', 30, 'New York'])

http://www.kler.cn/news/363342.html

相关文章:

  • 接口测试(四)jmeter——文件上传
  • 探索音频在线剪辑工具的奇妙世界
  • 【论文翻译】ICLR 2018 | DCRNN:扩散卷积递归神经网络:数据驱动的交通预测
  • Transformer 与 CNN的对比
  • 打开游戏提示丢失(或找不到)XINPUT1_3.DLL的多种解决办法
  • Pytorch 实现图片分类
  • 国内常见的 AI 工具,你都用过几个?
  • 【Android】自定义EditText
  • 交换基础简述
  • hive数据库,表操作
  • git 克隆并切换分支
  • 第九天 中间层异步编程
  • python 访问openai接口
  • 2024年软件设计师中级(软考中级)详细笔记【11】知识产权基础知识(分值2~3分)
  • 6、基于Python+爬虫+LDA+决策树的《富士山下》评论数据情感分析【开题+源程序+论文】
  • Spring Task介绍与基本使用
  • Konva框选移动
  • PPT自动化:掌握 python-pptx 的基础元素
  • 20240818 字节跳动 笔试
  • Python小游戏11——扑克牌消消看小游戏
  • Go入门指南-3.1Go 开发环境的基本要求
  • 哈夫曼树的定义?如何构造?
  • XJ03、消费金融|从场景实例看懂背后的系统架构
  • Xcode使用的一些问题记录
  • 图文深入介绍oracle资源管理(续)
  • Pyspark中pyspark.sql.functions常用方法(4)