Python内置数据结构
在这篇文章中,我们将学习Python中的4种内置数据结构:列表、字典、元组和集合。
列表
列表是有序的元素序列。它是一种非标量数据结构,并且是可变的。与存储相同数据类型元素的数组不同,列表可以包含不同数据类型。
可以通过在方括号中包含索引来访问列表。
现在让我们看一个例子来更好地理解列表。
示例
lis=['tutorialspoint',786,34.56,2+3j]
# displaying element of list
for i in lis:
print(i)
# adding an elements at end of list
lis.append('python')
#displaying the length of the list
print("length os list is:",len(lis))
# removing an element from the list
lis.pop()
print(lis)输出
tutorialspoint 786 34.56 (2+3j) length os list is: 5 ['tutorialspoint', 786, 34.56, (2+3j)]
元组
它也是在Python中定义的非标量类型。与列表一样,它也是有序的字符序列,但元组本质上是不可变的。这意味着不允许对这种数据结构进行任何修改。
元素可以是异构或同构的,用逗号分隔,括在括号内。
让我们来看一个例子。
示例
tup=('tutorialspoint',786,34.56,2+3j)
# displaying element of list
for i in tup:
print(i)
# adding elements at the end of the tuple will give an error
# tup.append('python')
# displaying the length of the list
print("length os tuple is:",len(tup))
# removing an element from the tup will give an error
# tup.pop()输出
tutorialspoint 786 34.56 (2+3j) length os tuple is: 4
集合
它是一个无序的对象集合,不包含任何重复项。这可以通过将所有元素括在花括号中来完成。我们也可以使用关键字“set”通过类型转换来形成集合。
集合的元素必须是不可变数据类型。集合不支持索引、切片、连接和复制。我们可以使用索引迭代元素。
现在让我们来看一个例子。
示例
set_={'tutorial','point','python'}
for i in set_:
print(i,end=" ")
# print the maximum and minimum
print(max(set_))
print(min(set_))
# print the length of set
print(len(set_))输出
tutorial point python tutorial point 3
字典
字典是键值对的无序序列。索引可以是任何不可变类型,称为键。这也用花括号指定。
我们可以通过与其关联的唯一键来访问值。
让我们来看一个例子。
示例
# Create a new dictionary d = dict() # Add a key - value pairs to dictionary d['tutorial'] = 786 d['point'] = 56 # print the min and max print (min(d),max(d)) # print only the keys print (d.keys()) # print only values print (d.values())
输出
point tutorial dict_keys(['tutorial', 'point']) dict_values([786, 56])
结论
在这篇文章中,我们学习了Python语言中存在的内置数据结构及其实现。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP