2017-05-04 28 views
0

我试图使用格式化字符串元组的列表,其中有以下形式:使用元组列表进行字符串格式化?

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)之类的东西直接“解开”列表和元组?

+2

您的预期输出是什么? –

+1

是您的最终查询应该是'SELECT'子句中的2个属性的硬编码长度? –

回答

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 
0

而是保存配方和标签成对的元组,你可以改为保存“时间在词典:

formulas_and_labels = {"formula1" : "1", "label1": "1a", 
         "formula2": "2", "label2": "2a" 
         } 

然后,你可以使用.format(**formulas_and_labels)符号你问,所提供的占位符都是正确的:

SQL_string = """SELECT 
         {formula1}  AS "{label1}", 
         {formula2}  AS "{label2}" 

       FROM 
       schema.table""" 

有鉴于此:

>>> print(SQL_string.format(**formulas_and_labels)) 
SELECT 
         1  AS "1a", 
         2  AS "2a" 

       FROM 
       schema.table 
相关问题