List Comprehension in Python, an example
Coding up a little website where a user would select (using check boxes) from a list of items and submit. I'm using Django btw (which is great). Due to the dynamic nature of the list being generated and displayed, the name of each checkbox wold be something like vid0, vid1, etc. The POST data however will not have the keys for unsubmitted values, and I have no way to tell which keys are in the POST dictionary.
So at first, I coded the following bit of code. Simple, straightforward, gets the job done.
There might be even simpler and more elegant solutions out there. If so, please leave them in the comments. (Maybe something using a lambda?)
BTW, I am a newcomer to python having started to code with it just a few months ago.
So at first, I coded the following bit of code. Simple, straightforward, gets the job done.
feed = []But then, I had a light bulb moment and coded this:
for i in range(max_results):
feed.append(request.POST.get('vid'+str(i), '')) # feed will contain empty strings
if feed[-1] is '':
del feed[-1] #if the most recently appended item is an empty string, delete it.
feed=[request.POST.get('vid'+str(i)) for i in range(max_results) if request.POST.get('vid'+str(i),'') is not '']One line of code now replaces 5! How awesome is that! Python rocks.There might be even simpler and more elegant solutions out there. If so, please leave them in the comments. (Maybe something using a lambda?)
BTW, I am a newcomer to python having started to code with it just a few months ago.
Labels: coding, django, list comprehension, POST data, programming, python, web requests


0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home