Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 505
Maximilian Kindshofer Avatar asked Dec 11 '22 21:12

Maximilian Kindshofer


2 Answers

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

items = [dicttolatex(dic) for dic in items_to_clean]
like image 57
juanchopanza Avatar answered Jan 08 '23 03:01

juanchopanza


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)
like image 44
The6thSense Avatar answered Jan 08 '23 03:01

The6thSense