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

列表(List)

Python中的列表类似于动态大小的数组,可以在不同的编程语言中声明,比如C++语言中的向量和Java语言中的ArrayList。在Python中,列表不需要是同质的,这个列表的特性使其成为Python的强大工具之一。

以下是列表的重要特点:

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

示例:

# let's see the Python code for demonstrating the List Data Structure.   
     
# First, we will create the List  
List = []  
print("javatiku 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 javatiku 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", "javatiku"]  
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", "javatiku", 78, 2, 1]  
List2 = [9, 3, 6, 19, 67, 78, "Hey", "javatiku", 2, 1]  
print("List1 = ", List1)  
print("List2 = ", List2)  
List1 == List2  

输出:

javatiku data List: 
[]

 The javatiku 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
javatiku
from

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

集合(Set)

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

以下是集合的重要特征:

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

示例:

# let's see the Python code for demonstrating the Set Data Structure.   
     
# First, we will create the Set  
setsetA = set()  
print("Intial javatiku Set: ")  
print(setA)  
     
# we are creating the Set by using Constructor  
# we will use object for Storing String)  
String = 'lets learn Python from javatiku'  
setsetA = set(String)  
print("\n Storing the set by using the Object: " )  
print(setA)  
     
# now, we will create the Set by using the list  
setsetA = set(["let's", "learn", "Python", "from", "javatiku"])  
print("\n Storing the set by using the List: ")  
print(setA)  

输出:

Intial javatiku 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: 
{'javatiku', "let's", 'learn', 'from', 'Python'}

列表与集合

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

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程