2

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?

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Your code would be more efficient if you used a generator instead of the list comprehension.
While it might be less efficient, you could also do something along the lines of ', '.join('SUM('+x+') AS '+x for x in a).
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.