使用以下代码:
a = ['foo', 'bar', 'doh', 'rae']
我想要字符串SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae
。这有效:
尝试像'SUM(%s) AS %s' % ([x for x in a], [x for x in a])
这样聪明的东西,但显然它没有用,并且使用两个列表推导感觉效率很低。
任何提示?
答案 0 :(得分:4)
为什么不使用str.format method?
", ".join(['SUM({n}) AS {n}'.format(n=x) for x in a])
# Returns SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae
如果a
是一个大型列表,您可能需要使用生成器,以避免首先在内存中创建整个列表,如GWW所指出的那样。
", ".join('SUM({n}) AS {n}'.format(n=x) for x in a)
答案 1 :(得分:0)
你可以使用str.format函数在一个字符串中传递一个两次争论,类似:
s = ', '.join(['SUM({0}) AS {0}'.format(x) for x in a])
并且通过一个列表推导和连接操作,它可以产生所需的输出
'SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae'
问候!