4

I want to clean the strings from a django query so it can be used in latex

items = []
items_to_clean = items.objects.get.all().values()
for dic in items_to_clean:
    items.append(dicttolatex(dic))

This is my standard aproach to this task. Can this somehow be solved whith list comprehension. since dicttolatex is a function returning a dict.

The6thSense
  • 8,103
  • 8
  • 31
  • 65
Maximilian Kindshofer
  • 2,753
  • 3
  • 22
  • 37

2 Answers2

8

You can avoid repeated calls to append by using a list comprehension:

items = [dicttolatex(dic) for dic in items_to_clean]
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
5

You could do use map why rediscover the wheel

Sample:

lst=[1,2,3,4]
def add(n):
    return n+n

a=[]
a.extend( map(add,lst))
print a

output:

[2, 4, 6, 8]

That is in your case :

items_to_clean = items.objects.get.all().values()
items = map(dicttolatex,items_to_clean)
Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65
  • this looks nice too, but I'll stick with juanchopanzas method since it creates the list and the values in one line of code – Maximilian Kindshofer Aug 13 '15 at 07:16
  • 2
    @MaximilianKindshofer `map` also creates the list with the values in only one line. It's even shorter... `items = map(dicttolatex, items_to_clean)` – Jakube Aug 13 '15 at 07:22
  • 2
    @MaximilianKindshofer If you're making a list, it is pretty much a matter of opinion which one is preferable. The generator expression used in the list comprehension can be used in different contexts when you don't necessarily need to build a list. See also http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map. Personally, I am used to list comprehensions and use them all the time, but map still seems easier to read, and easier to search for in source code. – juanchopanza Aug 13 '15 at 07:30