Python中List、Set和Tuple的区别
列表:列表就像动态大小的数组,用其他语言声明(C++ 中的向量和 Java 中的 ArrayList)。列表不必总是同质的,这使它成为 Python 中最强大的工具。列表的主要特点是 —
- 列表是 Python 中可用的一种数据类型,可以写成方括号之间的逗号分隔值(项目)列表。
- 列表是可变的。即它可以转换为另一种数据类型,并且可以在其中存储任何数据元素。
- 列表可以存储任何类型的元素。
# Python3 program to demonstrate # List # Creating a List List = [] print("Blank List: ") print(List) # Creating a List of numbers List = [10, 20, 14] print("List of numbers: ") print(List) # Creating a List of strings and accessing # using index List = ["geek-docs", "For", "Geeks"] print("List Items: ") print(List[0]) print(List[2])
运行结果:
Blank List: [] List of numbers: [10, 20, 14] List Items: geek-docs Geeks
元组:元组是 Python 对象的集合,很像列表。存储在元组中的值序列可以是任何类型,并且它们由整数索引。元组的值在语法上由“逗号”分隔。虽然没有必要,但更常见的是通过关闭括号中的值序列来定义元组。元组的主要特征是——
- 元组是python中的不可变序列。
- 它不能更改或替换,因为它是不可变的。
- 它在括号()下定义。
- 元组可以存储任何类型的元素。
示例代码:
# Creating an empty Tuple Tuple1 = () print("Initial empty Tuple: ") print (Tuple1) # Creating a Tuple with # the use of list list1 = [1, 2, 4, 5, 6] print("Tuple using List: ") print(tuple(list1)) #Creating a Tuple #with the use of built-in function Tuple1 = tuple('geek-docs') print("Tuple with the use of function: ") print(Tuple1)
运行结果:
Initial empty Tuple: () Tuple using List: (1, 2, 4, 5, 6) Tuple with the use of function: ('g', 'e', 'e', 'k', '-', 'd', 'o', 'c', 's')
Set: 在 Python 中,Set 是数据类型的无序集合,它是可迭代的、可变的,并且没有重复元素。与列表相比,使用集合的主要优点是它具有高度优化的方法来检查集合中是否包含特定元素。集合的主要特点是——
- 集合是python中元素的无序集合或项目的意外集合。
- 这里元素添加到集合中的顺序不是固定的,它可以经常变化。
- 在花括号{}下定义
- 集合是可变的,但是,只有不可变的对象可以存储在其中。
示例代码:
# Python3 program to demonstrate # Set in Python # Creating a Set set1 = set() print("Initial blank Set: ") print(set1) # Creating a Set with # the use of Constructor # (Using object to Store String) String = 'geek-docsForGeeks' set1 = set(String) print("Set with the use of an Object: " ) print(set1) # Creating a Set with # the use of a List set1 = set(["geek-docs", "For", "geek-docs"]) print("Set with the use of List: ") print(set1)
运行结果:
Initial blank Set: set() Set with the use of an Object: {'c', 's', 'G', 'F', '-', 'k', 'e', 'g', 'd', 'o', 'r'} Set with the use of List: {'geek-docs', 'For'}
列表、集合和元组之间的区别表:
列表 | 集合 | 元组 |
---|---|---|
Lists 是可变的 | Set 是可变的 | Tuple 是不可变的 |
项目的有序集合 | 项目的无序集合 | 项目的有序集合 |
列表中的项目可以替换或更改 | 集合中的项目不能更改或替换 | 元组中的项目不能更改或替换 |
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com