我试图使用带有元组列表的字符串格式,其格式如下:
formulas_and_labels = [('formula1', 'label1'),
('formula2', 'label2')]
这应该用于格式化以下字符串:
SQL_string = """SELECT
{} AS "{}",
{} AS "{}"
FROM
schema.table""".format(*formulas_and_labels)
我知道这会产生IndexError: tuple index out of range
,因为(*formulas_and_labels)
只包含两个元素(元组),而字符串需要4个元素(4x {})。
我首先使用
解压缩列表,找到了解决方法formulas_and_labels_unpacked = [v for t in formulas_and_labels for v in t]
(找到here)。
然而,我想知道是否有一种更直接的方式来直接"双解包"使用.format(**formulas_and_labels)
或.format(*el) for el in formulas_and_labels)
之类的列表和元组?
答案 0 :(得分:1)
您必须明确指出您所指的序列项,如下所示:
formulas_and_labels = [('formula1', 'label1'), ('formula2', 'label2')]
SQL_string = """SELECT
{0[0]} AS "{0[1]}",
{1[0]} AS "{1[1]}"
FROM
schema.table""".format(*formulas_and_labels)
print(SQL_string)
输出:
SELECT
formula1 AS "label1",
formula2 AS "label2"
FROM
schema.table
这可以通过根据formulas_and_labels
列表中有多少对值来动态创建所需的格式字符串来推广处理可变数量的公式和标签:
# Generalized
formulas_and_labels = [('formula1', 'label1'),
('formula2', 'label2'),
('formula3', 'label3')]
SQL_string = """SELECT
{}
FROM
schema.table"""
SELECT_string = '{{{0}[0]}} AS "{{{0}[1]}}"'
selects = ',\n '.join(SELECT_string.format(i)
for i in range(len(formulas_and_labels)))
print(SQL_string.format(selects.format(*formulas_and_labels)))
输出:
SELECT
formula1 AS "label1",
formula2 AS "label2",
formula3 AS "label3"
FROM
schema.table