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')