在本文中,我們將討論 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'}
列表與集合
| 列表 | 設置 |
| 列表是有序的。 | 集合是無序的。 |
| 列表是可變的。 | 集合是可變的,但只存儲不可變的元素。 |
| 可以在列表中更改或替換元素。 | 不能更改或替換元素。 |
原創文章,作者:D9QJE,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/130658.html