Maximilian Kindshofer
Maximilian Kindshofer

Reputation: 2843

Is there a more pythonic way to populate a this list?

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.

Upvotes: 4

Views: 154

Answers (2)

The6thSense
The6thSense

Reputation: 8335

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)

Upvotes: 5

juanchopanza
juanchopanza

Reputation: 227390

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

items = [dicttolatex(dic) for dic in items_to_clean]

Upvotes: 8

Related Questions