Wells
Wells

Reputation: 10979

python string formatting: way to not use two lists?

With the following code:

a = ['foo', 'bar', 'doh', 'rae']

I'd like the string SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae. This works:

Tried something clever like 'SUM(%s) AS %s' % ([x for x in a], [x for x in a]) but obviously it didn't work, and using two list comprehensions felt woefully inefficient.

Any tips?

Upvotes: 2

Views: 192

Answers (2)

Helbreder
Helbreder

Reputation: 922

you can use a str.format function to deliver one argumet twice in a string, something like that:

s = ', '.join(['SUM({0}) AS {0}'.format(x) for x in a])

and with one list comprehension and a join operation it produces desired output

'SUM(foo) AS foo, SUM(bar) AS bar, SUM(doh) AS doh, SUM(rae) AS rae'

Greetings!

Upvotes: 0

Sean Vieira
Sean Vieira

Reputation: 160063

Why not use the 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

If a is a large list, you may want to use a generator instead, in order to avoid creating the whole list in memory first, as GWW points out.

", ".join('SUM({n}) AS {n}'.format(n=x) for x in a)

Upvotes: 4

Related Questions