使用Python的for迴圈建立元組列表
Python 的關鍵資料結構是列表和元組。一旦元組的元素被設定,就不能更改。這稱為不變性。但是列表元素可以在初始化後修改。在處理需要組合在一起的資料時,使用 for 迴圈來建立元組列表。由於列表具有可修改性,因此列表比元組更具適應性。本教程演示瞭如何使用 for 迴圈建立元組列表,從而簡化重複性任務。
語法
for variable in iterable: # loop code
元組的基本操作
示例
# Initializing my_tuple = (1, 2, "Hello", 3.14) another_tuple = 10, 20, 30 print(another_tuple) # Output: (10, 20, 30) # Get elements my_tuple = (1, 2, 3, 4, 5) print(my_tuple[0]) # Output: 1 print(my_tuple[2]) # Output: 3 # Slicing elements my_tuple = (1, 2, 3, 4, 5) print(my_tuple[1:4]) # Output: (2, 3, 4) # Concatenation tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) combined_tuple = tuple1 + tuple2 # Output: (1, 2, 3, 4, 5, 6) # Tuple Size my_tuple = (1, 2, 3, 4, 5) print(len(my_tuple)) # Output: 5
輸出
(10, 20, 30) 1 3 (2, 3, 4) 5
用法
元組適合儲存建立後不應該修改的資料,例如配置或常量值。在從函式高效返回多個值時也很有用。
def get_coordinates():
x = 10
y = 20
return x, y
coordinates = get_coordinates()
# Output: coordinates = (10, 20)
# Can be unpacked into separate variables, making it easy to work with
their elements.
person = ("John", 30, "Developer")
name, age, profession = person
# Output: name = "John", age = 30, profession = "Developer"
# They are used as keys in dictionaries due to their immutability.
my_dict = {("John", 30): "USA", ("Alice", 25): "Canada"}
由於這種儲存的靈活性,元組用於函式和字典中。資料完整性是另一個好處。任何長度的單個元組都可以解包到一行程式碼中的多個變數中。
演算法
讓一個空列表儲存元組。
使用 for 迴圈迭代元素或物件。
對於每個條目,建立一個元組並將其新增到列表中。
示例 1
從員工姓名列表中建立一個包含員工姓名及其對應員工 ID 的元組列表。
employee_names = ["Alice", "Bob", "Charlie", "David", "Eva"] employee_ids = [101, 102, 103, 104, 105] employee_list = [] for i in range(len(employee_names)): employee_list.append((employee_names[i], employee_ids[i]))
解釋
對於元組,建立一個名為“employee_list”的空列表。for 迴圈迭代“employee_names”長度範圍,構建包含姓名和 ID 的元組。“employee_list”添加了新生成的元組。這會生成一個包含給定短語中單詞長度的元組列表。
# Example data sentence = "The quick brown fox jumps over the lazy dog" # Creating a list of tuples using a for loop word_length_list = [(word, len(word)) for word in sentence.split()]
應用
處理表格資料時,轉換行以提供結構,以便更好地進行資料管理和分析。
元組透過改進資料檢索和管理來增強資料庫操作,並透過合併姓名和 ID 等來源輕鬆進行資料配對。
結論
與列表不同,Python 中的元組是專案的已排序、不可變集合。一旦建立,就不能修改它。元組包含各種資料型別,包括整數、字串和浮點數。本指南演示瞭如何在 Python 中使用 for 迴圈建立元組列表。當您希望構建許多具有不同值的元組時,使用 for 迴圈生成元組列表可能很方便。for 迴圈允許遍歷元素列表,為每次迭代建立一個元組並將其新增到列表中。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP