Python 的数据类型有哪些?

数据类型是Python中的一个基本概念,可以针对不同类型的数据,执行不同的操作。在 Python 中一切都是对象,因此数据类型实际上是类,变量是这些类的实例(对象)。

Python 的数据类型有哪些?
Python 的数据类型有哪些?

以下是 Python 的标准数据类型:

数字

在 Python 中,数值数据类型表示具有数值的数据。数值可以是整数、浮点数和复数。这些值在 Python 中分别被定义为 intfloat complex

  • 整数(int)— 整数由 int 表示。它包含正整数或负整数(没有分数或小数)。在 Python 中,整数值的长度没有限制。
  • 浮点数(Float)— 浮点数由 Float 表示。它是一个带有浮点表示的实数。可以在一个正整数或负整数末尾加字符 e 或 E 来表示科学记数法。
  • 复数(complex)— 复数由 complex 表示。它被指定为(real part) + (imaginary part)j。例如 – 2+3j
Python program to
demonstrate numeric value
a = 5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))

output:

Type of a:  
Type of b:  
Type of c:  

序列类型

在 Python 中,序列不同数据类型的有序集合。序列允许以有组织和有效的方式存储多个值。Python中有几种序列类型:

1) 字符串

在 Python 中,字符串是表示 Unicode 字符的字节数组。字符串是放在单引号、双引号或三引号中的一个或多个字符的集合。在 python 中没有字符数据类型,字符是长度为 1 的字符串。它由 str 表示。
 

创建字符串

Python 中的字符串可以使用单引号或双引号甚至三引号来创建。

Python Program for
Creation of String
Creating a String
with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
Creating a String
with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
Creating a String
with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
Creating String with triple
Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

output:

 String with the use of Single Quotes: 
 Welcome to the Geeks World
 String with the use of Double Quotes: 
 I'm a Geek
 
 String with the use of Triple Quotes: 
 I'm a Geek and I live in a world of "Geeks"
 
 Creating a multiline String: 
 Geeks 
             For 
             Life

访问字符串的元素

在 Python 中,可以使用 Indexing 方法访问字符串的各个字符。索引允许负地址引用从字符串后面访问字符,例如,-1 指的是最后一个字符,-2 指的是倒数第二个字符,依此类推。

Python 字符串索引
Python Program to Access
characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
Printing First character
print("\nFirst character of String is: ")
print(String1[0])
Printing Last character
print("\nLast character of String is: ")
print(String1[-1])

output:

 Initial String: 
 GeeksForGeeks
 First character of String is: 
 G
 Last character of String is: 
 s

2) 列表

列表就像数组一样,用其他语言声明,是有序的数据集合。它非常灵活,因为列表中的项目不需要属于同一类型。
 

创建列表

Python 中的列表只需将序列放在方括号内即可创建[]

Python program to demonstrate
Creation of List
Creating a List
List = []
print("Initial blank List: ")
print(List)
Creating a List with
the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)
Creating a List with
the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
Creating a Multi-Dimensional List
(By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)

output:

 Initial blank List: 
 []
 List with the use of String: 
 ['GeeksForGeeks']
 List containing multiple values: 
 Geeks
 Geeks
 Multi-Dimensional List: 
 [['Geeks', 'For'], ['Geeks']]

访问 List 的元素

为了访问列表项,请参阅索引号。使用索引运算符[ ]访问列表中的项目。在 Python 中,负序索引表示从数组末尾开始的位置。不必像List[len(List)-3]中那样计算偏移量,只需编写List[-3]. 负索引表示从末尾开始,-1 指最后一项,-2 指倒数第二项,依此类推。

Python program to demonstrate
accessing of element from list
Creating a List with
the use of multiple values
List = ["Geeks", "For", "Geeks"]
accessing a element from the
list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])
accessing a element using
negative indexing
print("Accessing element using negative indexing")
print the last element of list
print(List[-1])
print the third last element of list
print(List[-3])

output:

 Accessing element from the list
 Geeks
 Geeks
 Accessing element using negative indexing
 Geeks
 Geeks

3) 元组

就像列表一样,元组也是 Python 对象的有序集合。元组和列表之间的唯一区别是元组是不可变的,即元组在创建后不能修改。它由 tuple 表示。
 

创建元组

在 Python 中,通过放置由“逗号”分隔的值序列来创建元组,可以使用或不使用括号对数据序列进行分组。元组可以包含任意数量的元素和任何数据类型(如字符串、整数、列表等)。

注意:也可以使用单个元素创建元组,但这有点棘手。括号中只有一个元素是不够的,必须有一个尾随的“逗号”才能使其成为元组。

Python program to demonstrate
creation of Set
Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
Creating a Tuple with
the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
Creating a Tuple with
the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Creating a Tuple with the
use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
Creating a Tuple
with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

output:

 Initial empty Tuple: 
 ()
 Tuple with the use of String: 
 ('Geeks', 'For')
 Tuple using List: 
 (1, 2, 4, 5, 6)
 Tuple with the use of function: 
 ('G', 'e', 'e', 'k', 's')
 Tuple with nested tuples: 
 ((0, 1, 2, 3), ('python', 'geek'))

注意——不使用括号创建 Python 元组被称为元组打包。

访问元组的元素

可以使用索引运算符[]访问元组中的项目。索引必须是整数。使用嵌套索引访问嵌套元组。

Python program to
demonstrate accessing tuple
tuple1 = tuple([1, 2, 3, 4, 5])
Accessing element using indexing
print("First element of tuple")
print(tuple1[0])
Accessing element from last
negative indexing
print("\nLast element of tuple")
print(tuple1[-1])
print("\nThird last element of tuple")
print(tuple1[-3])

output:

 First element of tuple
 1
 Last element of tuple
 5
 Third last element of tuple
 3

布尔值

布尔值有两个内置值 TrueFalse。返回 True 的布尔对象为真 (true),返回 False 的布尔对象为假 (false)。需要注意的是 True 和 False 的首字母要大写,否则 python 会提示错误。

Python program to
demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))

output:

<class 'bool'> 
<class 'bool'>
Traceback (most recent call last):
   File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in 
     print(type(true))
NameError: name 'true' is not defined

集合

在 Python 中,集合是数据类型的无序集合,它是可迭代的、可变的并且没有重复元素。集合中元素的顺序是不确定的,尽管它可能由各种元素组成。

创建集合

可以使用 set()函数来创建集合,方法是将序列放在{}内,用“逗号”分隔。集合中元素的类型不必相同,也可以将各种混合的数据类型值传递给集合。

Python program to demonstrate
Creation of Set in Python
Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
Creating a Set with
the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
Creating a Set with
the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)
Creating a Set with
a mixed type of values
(Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)

output:

 Initial blank Set: 
 set()
 Set with the use of String: 
 {'F', 'o', 'G', 's', 'r', 'k', 'e'}
 Set with the use of List: 
 {'Geeks', 'For'}
 Set with the use of Mixed Values
 {1, 2, 4, 6, 'Geeks', 'For'}

访问集合的元素

集合项不能通过引用索引来访问,因为集合是无序的,这些项没有索引。但是可以使用 for 循环遍历集合项,或者使用in 查询集合中是否存在特定值。

Python program to demonstrate
Accessing of elements in a set
Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)
Accessing element using
for loop
print("\nElements of set: ")
for i in set1:
print(i, end =" ")
Checking the element
using in keyword
print("Geeks" in set1)

output:

 Initial set: 
 {'Geeks', 'For'}
 Elements of set: 
 Geeks For 
 True

字典

Python 中的字典是数据值的无序集合,与其他只保存单个值作为元素的数据类型不同,字典保存的是 key:value 对。字典中的每个键值对由冒号分隔:,而每个键由“逗号”分隔。

创建字典

在 Python 中,可以通过在大{}括号内放置一系列元素来创建字典,并用“逗号”分隔。字典中的值可以是任何数据类型并且可以重复,而键不能重复并且必须是不可变的。字典也可以通过内置函数 dict() 创建。只需将其放在花括号{} 中即可创建一个空字典。

注意:字典键区分大小写,相同名称但不同大小写的 Key 将被区别对待。

Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Creating a Dictionary
with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Creating a Dictionary
with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Creating a Dictionary
with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Creating a Dictionary
with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

output:

 Empty Dictionary: 
 {}
 Dictionary with the use of Integer Keys: 
 {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 Dictionary with the use of Mixed Keys: 
 {1: [1, 2, 3, 4], 'Name': 'Geeks'}
 Dictionary with the use of dict(): 
 {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 Dictionary with each item as a pair: 
 {1: 'Geeks', 2: 'For'}

访问字典的元素

可以根据键的值,来访问字典的元素。还可以使用 get()函数从字典中查询元素。

Python program to demonstrate
accessing a element from a Dictionary
Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
accessing a element using get()
method
print("Accessing a element using get:")
print(Dict.get(3))

output:

 Accessing a element using key:
 For
 Accessing a element using get:
 Geeks

作者:牛奇网,本站文章均为辛苦原创,在此严正声明,本站内容严禁采集转载,面斥不雅请好自为之,本文网址:https://www.niuqi360.com/python/python-data-types/

(0)
牛奇网牛奇网
上一篇 2022年1月12日 上午10:10
下一篇 2022年1月13日 上午10:57

发表回复

登录后才能评论
很多新手不知道如何选择外贸独立站主机,这里推荐一款使用量最大,性价比最高的国外独立站主机Hostinger,立即获取优惠