首页 > 编程知识 正文

Python 中集合和列表的区别

时间:2023-11-25 15:30:20 阅读:309252 作者:NWDP

在本文中,我们将讨论 Python 中集合和列表的区别。集合和列表是 Python 中的数据结构,用于以有效的方式存储和组织数据。

目录

Python 中的列表就像是一个动态大小的数组,可以用不同的语言来声明,比如 C++语言中的vector和 Java 语言中的ArrayList。Python 中的列表并不是一定要同质化的,列表的这个特性让它成为了 Python 的强大工具之一。

以下是 list 的重要特征:

  • 它是 Python 提供的数据类型。用户可以将其写成列表,列表的值可以用逗号分隔,并写在方括号之间。
  • 它可以转换成不同的数据类型,用户可以在其中存储任何数据元素。因此,列表是可变的。
  • 这是命令。

示例:


# let's see the Python code for demonstrating the List Data Structure. 

# First, we will create the List
List = []
print("JavaTpoint data List: ")
print(List)

# we are creating the List of numbers
List = [12, 24, 64, 18, 3, 201, 65, 35, 27, 29, 58, 42, 87, 30, 28, 79, 4, 90]
print("n The JavaTpoint List of numbers: ")
print(List)

# Now, we will create the List of strings and will access it using index method.

List = ["let's", "learn", "Python", "from", "JavaTpoint"]
print("nList Items: ")
print(List[0]) 
print(List[2])
print(List[1])
print(List[4])
print(List[3])
# Now we will check is list are ordered

List1 = [9, 3, 6, 19, 67, "Hey", "JavaTpoint", 78, 2, 1]
List2 = [9, 3, 6, 19, 67, 78, "Hey", "JavaTpoint", 2, 1]
print("List1 = ", List1)
print("List2 = ", List2)
List1 == List2

输出:

JavaTpoint data List: 
[]

 The JavaTpoint List of numbers: 
[12, 24, 64, 18, 3, 201, 65, 35, 27, 29, 58, 42, 87, 30, 28, 79, 4, 90]

List Items: 
let's
Python
learn
JavaTpoint
from

List1 =  [9, 3, 6, 19, 67, 'Hey', 'JavaTpoint', 78, 2, 1]
List2 =  [9, 3, 6, 19, 67, 78, 'Hey', 'JavaTpoint', 2, 1]
False

一组

集合是 Python 中数据类型的无序集合,具有可变性和可迭代性。集合没有任何相同元素的重复。与列表相比,在 Python 中使用集合数据存储工具的一个主要优势是,它提供了高度优化的方法来检查集合中特定项目的存在。

以下是 set 的重要特性:

  • 它是 Python 中项目或数据类型的无序集合。
  • 存储在其中的元素的顺序不是固定的。集合元素的顺序可以改变。
  • 花括号{ }之间定义了一组元素。
  • 虽然只有不可变的元素存储在集合中,但它是可变的。

示例:


# let's see the Python code for demonstrating the Set Data Structure. 

# First, we will create the Set
setA = set()
print("Intial JavaTpoint Set: ")
print(setA)

# we are creating the Set by using Constructor
# we will use object for Storing String)
String = 'lets learn Python from JavaTpoint'
setA = set(String)
print("n Storing the set by using the Object: " )
print(setA)

# now, we will create the Set by using the list
setA = set(["let's", "learn", "Python", "from", "JavaTpoint"])
print("n Storing the set by using the List: ")
print(setA)

输出:

Intial JavaTpoint Set: 
set()

 Storing the set by using the Object: 
{'t', 'v', 'a', 'r', 'T', 'l', 'n', 'y', 'e', ' ', 'h', 'P', 'p', 'f', 'o', 's', 'i', 'J', 'm'}

 Storing the set by using the List: 
{'JavaTpoint', "let's", 'learn', 'from', 'Python'}

列表与集合

| 列表 | 设置 | | 列表是有序的。 | 集合是无序的。 | | 列表是可变的。 | 集合是可变的,但只存储不可变的元素。 | | 可以在列表中更改或替换元素。 | 不能更改或替换元素。 |


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。