如何在 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')
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP