跳至主要內容

01-初探 Python 数据类型

AI悦创原创轻松入门 Python—玩中学轻松入门 Python—玩中学大约 3 分钟...约 820 字

1. 一图胜千言

DataType
DataType

2. 数字型

2.1 整型「int」

x = 1
# 检测数据类型方法一
t = type(x)
print(t)

# 检测数据类型方法二
print(type(x))

# ------output------
<class 'int'>
<class 'int'>

2.2 浮点型「float」

3. 字符串「str」

4. 列表「list」

5. 元组「tuple」

6. 字典「dict」

字典是由一系列的 key 与 value 组成的,d = {key1: value1, key2: value2}。我们可以创建如下字典:

d1 = {"name": "bornforthis", "age": 18, "gender": "F"}
d2 = {1: "number", (1, 2, 3): "tuple", True: "bool"}

# 检测数据类型
d1_type = type(d1)
d2_type = type(d2)
print("d1_type:", d1_type)
print("d2_type:", d2_type)

print(d1)
print(d2)

# ------output------
d1_type: <class 'dict'>
d2_type: <class 'dict'>
{'name': 'bornforthis', 'age': 18, 'gender': 'F'}
{1: 'bool', (1, 2, 3): 'tuple'}

6.1 字典创建规则

  1. key:字典中,key 需使用不可变的数据类型。如果使用可变数据类型,将会报错:TypeError: unhashable type: 'list'
    1. 列表、字典、集合皆不能做字典的 key
  2. value:任意数据类型
代码
d3 = {[1, 2, 3]: "number"}
print(d3)

6.2 字典的特性:

  • 字典是一系列由键(key)和值(value)配对组成的元素的集合;
  • 在 Python3.7+,字典被确定为有序(注意:在 3.6 中,字典有序是一个 implementation detail,在 3.7 才正式成为语言特性,因此 3.6 中无法 100% 确保其有序性),而 3.6 之前是无序的;
  • 字典长度大小可变,元素可以任意地删减和改变。

提示

字典有序性和以往(列表、字符串、元组等)有序性不同。零基础小白,前期理解为无序即可。「因为,你目前用不到此特性」

7. 集合「set」

set1 = {1, 2, 3, "aiyc", (1, 2, 3), True, False, 1.1}
print(type(set1))
print(set1)

# ------output------
<class 'set'>
{False, 1, 2, 3, 1.1, 'aiyc', (1, 2, 3)}

7.1 集合的特性

  • 确定性:每一个值都必须是确定的
  • 无序性:没有顺序
  • 互异性:不能相同,相同的会自动去除「去重」
集合确定性解析

集合确定性解析

列表可变,所以导致列表不确定。

举个例子🌰:

  • 在 1s 的时,列表数据为:lst = [1, 2, 3]
  • 在 1.6s 时,列表数据为:lst = [1, 2]

那我们是否可以说:我确定,列表数据一直都是 [1, 2, 3] 。——这句话显然是不合理。

8. 布尔型「bool」

a = True
b = False
print(type(a))
print(type(b))

print(a)
print(b)

# ------output------
<class 'bool'>
<class 'bool'>
True
False
上次编辑于:
贡献者: AI悦创
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度