Python 元组转换为列表

直接将元组转为列表

tup = (21, 19, 11, 46, 18)
print(tup)

lt = list(tup)
print(lt)

输出

(21, 19, 11, 46, 18)
[21, 19, 11, 46, 18]

将元组列表转为列表

# List of tuple initialization
listoftuples = [("Apple", 1), ("Microsoft", 2), ("Amazon", 3)]

# Using list comprehension
out = [item for t in listoftuples for item in t]

# Printing output
print(out)

输出

['Apple', 1, 'Microsoft', 2, 'Amazon', 3]

还可以使用 itertools.chain() 方法将元组列表转换为列表。

# Importing itertools
import itertools

# List of tuple initialization
tuple = [(11, 21), (31, 41), (51, 61)]
# tuple = [(11, ), (31, ), (51, )] 这种方式在链接数据库查询ID时得到的元组,可以转为列表,很方便
# Using itertools
out = list(itertools.chain(*tuple))

# Printing output
print(out)

输出

[11, 21, 31, 41, 51, 61]

结论:当给定一个可迭代对象(如列表、元组、集合、范围等)时,list() 和 tuple() 返回一个新的列表和元组

posted @ 2022-11-10 13:54  darling331  阅读(310)  评论(0编辑  收藏  举报