📅  最后修改于: 2023-12-03 15:11:13.598000             🧑  作者: Mango
在 Python 中,元组是不可变的有序序列,元组列表是一个元组组成的列表。生成元组列表是 Python 中一种非常常见的操作,可以用来构建数据集,进行多维数组的操作等等。
使用列表推导式,可以很方便地将任意序列(列表、元组、集合)转化为元组列表。
my_tuple_list = [tuple(item) for item in my_list]
使用 map() 函数,可以将一个可迭代对象映射成一个新的元组列表。
my_tuple_list = list(map(tuple, my_list))
使用 zip() 函数,可以将多个可迭代对象合并成一个元组列表。zip() 函数返回一个迭代器,需要使用 list() 函数将其转换为元组列表。
my_tuple_list = list(zip(my_tuple_1, my_tuple_2, my_tuple_3))
my_array = [(1, 2), (3, 4), (5, 6)]
for row in my_array:
for col in row:
print(col)
my_dataset = [
('张三', '男', 22),
('李四', '女', 25),
('王五', '男', 28),
]
for name, gender, age in my_dataset:
print(f"{name} 的性别是 {gender},年龄是 {age} 岁。")
import sqlite3
with sqlite3.connect('my_database.db') as conn:
cur = conn.cursor()
cur.execute('''CREATE TABLE person
(name text, gender text, age int)''')
my_dataset = [
('张三', '男', 22),
('李四', '女', 25),
('王五', '男', 28),
]
cur.executemany('INSERT INTO person VALUES (?,?,?)', my_dataset)