如何在 Python 中轉換元組和列表?
首先,我們來了解如何在 Python 中將元組轉換成列表。
將包含整數元素的元組轉換成列表
要將元組轉換成列表,請使用 list() 方法,並將要轉換的元組作為引數設定。
示例
讓我們來看看示例
# Creating a Tuple mytuple = (20, 40, 60, 80, 100) # Displaying the Tuple print("Tuple = ",mytuple) # Length of the Tuple print("Tuple Length= ",len(mytuple)) # Tuple to list mylist = list(mytuple) # print list print("List = ",mylist) print("Type = ",type(mylist))
輸出
Tuple = (20, 40, 60, 80, 100) Tuple Length= 5 List = [20, 40, 60, 80, 100] Type = <class 'list'>
將包含字串元素的元組轉換成列表
要將元組轉換成列表,請使用 list() 方法,並將要轉換的包含字串元素的元組作為引數設定。
示例
讓我們來看看示例
# Creating a Tuple mytuple = ("Jacob", "Harry", "Mark", "Anthony") # Displaying the Tuple print("Tuple = ",mytuple) # Length of the Tuple print("Tuple Length= ",len(mytuple)) # Tuple to list mylist = list(mytuple) # print list print("List = ",mylist) print("Type = ",type(mylist))
輸出
Tuple = ('Jacob', 'Harry', 'Mark', 'Anthony') Tuple Length= 4 List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Type = <class 'list'>
將列表轉換成元組
要將列表轉換成元組,請使用 tuple() −
示例
# Creating a List mylist = ["Jacob", "Harry", "Mark", "Anthony"] # Displaying the List print("List = ",mylist) # Convert List to Tuple res = tuple(mylist) print("Tuple = ",res)
輸出
List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Tuple = ('Jacob', 'Harry', 'Mark', 'Anthony')
廣告