title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Python library to modify MP3 audio without transcoding | 310,765 | <p>I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase.</p>
<p>My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be convinced otherwise).</p>
<p>I would like to modify a set of mp3 files in a fairly simple way. I am not so much interested in the ID3 tags but in the audio itself. I want to be able to delete sections (e.g. drop 10 seconds from the 3rd minute), and insert sections (e.g. add credits to the end.)</p>
<p>My understanding is that the mp3 format is lossy, and so decoding it to (for example) PCM format, making the modifications, and then encoding it again to MP3 will lower the audio quality. (I would love to hear that I am wrong.)</p>
<p>I <em>conjecture</em> that if I stay in mp3 format, there will be some sort of minimum frame or packet-size to deal with, so the granularity of the operations may be coarser. I can live with that, as long as I get an accuracy of within a couple of seconds.</p>
<p>I have looked at <a href="http://pymedia.org/">PyMedia</a>, but it requires me to migrate to PCM to process the data. Similarly, <a href="http://lame.sourceforge.net">LAME</a> wants to help me encode, but not access the data in place. I have seen several other libraries that only deal with the ID3 tags.</p>
<p>Can anyone recommend a Python MP3 library? Alternatively, can you disabuse me of my assumption that going to PCM and back is bad and avoidable?</p>
| 16 | 2008-11-22T02:30:54Z | 310,799 | <p>Not a direct answer to your needs, but check the <a href="http://mpesch3.de1.cc/mp3dc.html#dwn" rel="nofollow">mp3DirectCut</a> software that does what you want (as a GUI app). I think that the source code is available, so even if you don't find a library, you could build one of your own, or build a python extension using code from mp3DirectCut.</p>
| 1 | 2008-11-22T03:16:23Z | [
"python",
"mp3",
"codec"
]
|
Python library to modify MP3 audio without transcoding | 310,765 | <p>I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase.</p>
<p>My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be convinced otherwise).</p>
<p>I would like to modify a set of mp3 files in a fairly simple way. I am not so much interested in the ID3 tags but in the audio itself. I want to be able to delete sections (e.g. drop 10 seconds from the 3rd minute), and insert sections (e.g. add credits to the end.)</p>
<p>My understanding is that the mp3 format is lossy, and so decoding it to (for example) PCM format, making the modifications, and then encoding it again to MP3 will lower the audio quality. (I would love to hear that I am wrong.)</p>
<p>I <em>conjecture</em> that if I stay in mp3 format, there will be some sort of minimum frame or packet-size to deal with, so the granularity of the operations may be coarser. I can live with that, as long as I get an accuracy of within a couple of seconds.</p>
<p>I have looked at <a href="http://pymedia.org/">PyMedia</a>, but it requires me to migrate to PCM to process the data. Similarly, <a href="http://lame.sourceforge.net">LAME</a> wants to help me encode, but not access the data in place. I have seen several other libraries that only deal with the ID3 tags.</p>
<p>Can anyone recommend a Python MP3 library? Alternatively, can you disabuse me of my assumption that going to PCM and back is bad and avoidable?</p>
| 16 | 2008-11-22T02:30:54Z | 310,817 | <p>If you want to do things low-level, use <a href="http://spacepants.org/src/pymad/" rel="nofollow">pymad</a>. It turns MP3s into a buffer of sample data.</p>
<p>If you want something a little higher-level, use the Echo Nest <a href="http://code.google.com/p/echo-nest-remix/" rel="nofollow">Remix API</a> (disclosure: I wrote part of it for my dayjob). It includes a few examples. If you look at the <a href="http://code.google.com/p/echo-nest-remix/source/browse/#svn/trunk/examples/cowbell" rel="nofollow">cowbell</a> example (i.e., <a href="http://morecowbell.dj" rel="nofollow">MoreCowbell.dj</a>), you'll see a fork of pymad that gives you a <a href="http://numpy.scipy.org/" rel="nofollow">NumPy</a> array instead of a buffer. That datatype makes it easier to slice out sections and do math on them.</p>
| 8 | 2008-11-22T03:35:23Z | [
"python",
"mp3",
"codec"
]
|
Python library to modify MP3 audio without transcoding | 310,765 | <p>I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase.</p>
<p>My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be convinced otherwise).</p>
<p>I would like to modify a set of mp3 files in a fairly simple way. I am not so much interested in the ID3 tags but in the audio itself. I want to be able to delete sections (e.g. drop 10 seconds from the 3rd minute), and insert sections (e.g. add credits to the end.)</p>
<p>My understanding is that the mp3 format is lossy, and so decoding it to (for example) PCM format, making the modifications, and then encoding it again to MP3 will lower the audio quality. (I would love to hear that I am wrong.)</p>
<p>I <em>conjecture</em> that if I stay in mp3 format, there will be some sort of minimum frame or packet-size to deal with, so the granularity of the operations may be coarser. I can live with that, as long as I get an accuracy of within a couple of seconds.</p>
<p>I have looked at <a href="http://pymedia.org/">PyMedia</a>, but it requires me to migrate to PCM to process the data. Similarly, <a href="http://lame.sourceforge.net">LAME</a> wants to help me encode, but not access the data in place. I have seen several other libraries that only deal with the ID3 tags.</p>
<p>Can anyone recommend a Python MP3 library? Alternatively, can you disabuse me of my assumption that going to PCM and back is bad and avoidable?</p>
| 16 | 2008-11-22T02:30:54Z | 313,181 | <p>I got three quality answers, and I thank you all (and upvoted you all) for them. I haven't chosen any as the accepted answer, because each addressed one aspect, so I wanted to write a summary.</p>
<p><strong>Do you need to work in MP3?</strong></p>
<ul>
<li><p>Transcoding to PCM and back to MP3 is unlikely to result in a drop in quality. </p></li>
<li><p>Don't optimise audio-quality prematurely; test it with a simple prototype and listen to it.</p></li>
</ul>
<p><strong>Working in MP3</strong></p>
<ul>
<li><p>Wikipedia has a summary of the <a href="http://en.wikipedia.org/wiki/MP3">MP3 File Format</a>.</p></li>
<li><p>MP3 frames are short (1152 samples, or just a few milliseconds) allowing for moderate precision at that level.</p></li>
<li><p>However, <a href="http://en.wikipedia.org/wiki/MP3">Wikipedia</a> warns that "Frames are not independent items ("byte reservoir") and therefore cannot be extracted on arbitrary frame boundaries."</p></li>
<li><p>Existing libraries are unlikely to be of assistance, if I really want to avoid decoding.</p></li>
</ul>
<p><strong>Working in PCM</strong></p>
<p>There are several libraries at this level:</p>
<ul>
<li><a href="http://pymedia.org/">PyMedia</a></li>
<li><a href="http://lame.sourceforge.net/">LAME</a></li>
<li><a href="http://spacepants.org/src/pymad/">PyMad</a> (Linux only? Decoder only?)</li>
</ul>
<p><strong>Working at a higher level</strong></p>
<ul>
<li><p><a href="http://code.google.com/p/echo-nest-remix/">Echo Nest Remix API</a> (Mac or Linux only, at the moment) is an API to a web-service that supports quite sophisticated operations (e.g. finding the locations of music beats and tempo, etc.)</p></li>
<li><p><a href="http://mpesch3.de1.cc/mp3dc.html#dwn">mp3DirectCut</a> (Windows only) is a GUI that apparently performs the operations I want, but as an app. It is not open-source. (I tried to run it, got an Access Denied installer error, and didn't follow up. A GUI isn't suitably for me, as I want to repeatedly run these operations on a changing library of files.) </p></li>
</ul>
<p>My plan is now to start out in PyMedia, using PCM. Thank you all for your assistance.</p>
| 6 | 2008-11-24T00:42:43Z | [
"python",
"mp3",
"codec"
]
|
Python library to modify MP3 audio without transcoding | 310,765 | <p>I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase.</p>
<p>My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be convinced otherwise).</p>
<p>I would like to modify a set of mp3 files in a fairly simple way. I am not so much interested in the ID3 tags but in the audio itself. I want to be able to delete sections (e.g. drop 10 seconds from the 3rd minute), and insert sections (e.g. add credits to the end.)</p>
<p>My understanding is that the mp3 format is lossy, and so decoding it to (for example) PCM format, making the modifications, and then encoding it again to MP3 will lower the audio quality. (I would love to hear that I am wrong.)</p>
<p>I <em>conjecture</em> that if I stay in mp3 format, there will be some sort of minimum frame or packet-size to deal with, so the granularity of the operations may be coarser. I can live with that, as long as I get an accuracy of within a couple of seconds.</p>
<p>I have looked at <a href="http://pymedia.org/">PyMedia</a>, but it requires me to migrate to PCM to process the data. Similarly, <a href="http://lame.sourceforge.net">LAME</a> wants to help me encode, but not access the data in place. I have seen several other libraries that only deal with the ID3 tags.</p>
<p>Can anyone recommend a Python MP3 library? Alternatively, can you disabuse me of my assumption that going to PCM and back is bad and avoidable?</p>
| 16 | 2008-11-22T02:30:54Z | 790,833 | <p>As for removing or extracting mp3 segments from an mp3 file while staying in the MP3 domain (that is, without conversion to PCM format and back), there is also the open source package <a href="http://sourceforge.net/projects/pymp3cut/" rel="nofollow">PyMp3Cut</a>. </p>
<p>As for splicing MP3 files together (adding e.g. 'Credits' to the end or beginning of an mp3 file) I've found you can simply concatenate the MP3 files providing that the files have the same sampling rate (e.g. 44.1khz) and the same number of channels (e.g. both are stereo or both are mono).</p>
| 1 | 2009-04-26T13:13:34Z | [
"python",
"mp3",
"codec"
]
|
using rstrip on form.cleaned_data[i] in Django | 310,833 | <p>In my views.py, i have a snippit of code like this:</p>
<pre><code>def clean_post_data(form):
for i in form.cleaned_data:
form.cleaned_data[i] = form.cleaned_data[i].rstrip()
def add_product(request):
form = ProductForm(request.POST, request.FILES or None)
image = Image.objects.all()
action = "Add"
if request.POST:
if form.is_valid():
clean_post_data(form)
form.save()
action = "Added new product"
return render_to_response('cms/admin/action.html', {'action' : action},context_instance=RequestContext(request))
else:
action = "There was an error. Please go back and try again"
return render_to_response('cms/admin/action.html', {'action' : action}, context_instance=RequestContext(request))
return render_to_response('cms/admin/editproduct.html', {'form' : form, 'action' : action, 'image' : image}, context_instance=RequestContext(request))
</code></pre>
<p>But when i run that, i get the following error <code>'list' object has no attribute 'rstrip'</code>. What am i doing wrong.</p>
<p>I originally had the <code>for i in form.cleaned_data:</code> loop directly in the view (not in another function) and it worked fine, but now when i try it i get the same error as above. <a href="http://dpaste.com/92836/" rel="nofollow">http://dpaste.com/92836/</a></p>
| 1 | 2008-11-22T04:02:49Z | 310,900 | <p>Most likely you have several elements on your form with same name. When it is submitted one of the elements returned by cleaned_data is a list</p>
<p>If you want to skip (or do something special about) such cases you need to check for it:</p>
<pre>
def clean_post_data(form):
for i in form.cleaned_data:
if('__iter__' in dir(form.cleaned_data[i])):
print "skip this element: " + str(form.cleaned_data[i])
else:
form.cleaned_data[i] = form.cleaned_data[i].rstrip()
</pre>
| 0 | 2008-11-22T05:07:47Z | [
"python",
"django"
]
|
using rstrip on form.cleaned_data[i] in Django | 310,833 | <p>In my views.py, i have a snippit of code like this:</p>
<pre><code>def clean_post_data(form):
for i in form.cleaned_data:
form.cleaned_data[i] = form.cleaned_data[i].rstrip()
def add_product(request):
form = ProductForm(request.POST, request.FILES or None)
image = Image.objects.all()
action = "Add"
if request.POST:
if form.is_valid():
clean_post_data(form)
form.save()
action = "Added new product"
return render_to_response('cms/admin/action.html', {'action' : action},context_instance=RequestContext(request))
else:
action = "There was an error. Please go back and try again"
return render_to_response('cms/admin/action.html', {'action' : action}, context_instance=RequestContext(request))
return render_to_response('cms/admin/editproduct.html', {'form' : form, 'action' : action, 'image' : image}, context_instance=RequestContext(request))
</code></pre>
<p>But when i run that, i get the following error <code>'list' object has no attribute 'rstrip'</code>. What am i doing wrong.</p>
<p>I originally had the <code>for i in form.cleaned_data:</code> loop directly in the view (not in another function) and it worked fine, but now when i try it i get the same error as above. <a href="http://dpaste.com/92836/" rel="nofollow">http://dpaste.com/92836/</a></p>
| 1 | 2008-11-22T04:02:49Z | 311,304 | <p>The <code>clean_post_data</code> shouldn't be a stand-alone function.</p>
<p>It should be a method in the form, named <code>clean</code>. See <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation" rel="nofollow">Form and Field Validation</a>.</p>
| 1 | 2008-11-22T12:46:33Z | [
"python",
"django"
]
|
Python GTK MVC | 310,856 | <p>I've been looking around for a good MVC framework for Python using PyGTK. I've looked at <a href="http://www.async.com.br/projects/kiwi/" rel="nofollow">Kiwi</a> but found it a bit lacking, especially with using the Gazpacho Glade-replacement.</p>
<p>Are there any other nice desktop Python MVC frameworks? I'm one of the few (it seems) to not want a webapp.</p>
| 2 | 2008-11-22T04:26:23Z | 310,922 | <p>There's <a href="http://stackoverflow.com/questions/310856/python-gtk-mvc">Dabo</a>, made by some guys moving from FoxPro. It might work for you if you're writing a data driven business app.</p>
<p>Beyond that, I haven't found anything that you haven't.</p>
<blockquote>
<p>GUI stuff is <em>supposed</em> to be hard. It builds character.</p>
</blockquote>
<p>(<a href="http://www.amk.ca/quotations/python-quotes/" rel="nofollow">Attributed</a> to Jim Ahlstrom, at one of the early Python workshops. Unfortunately, things haven't changed much since then.)</p>
| 1 | 2008-11-22T05:36:47Z | [
"python",
"model-view-controller",
"gtk"
]
|
Python GTK MVC | 310,856 | <p>I've been looking around for a good MVC framework for Python using PyGTK. I've looked at <a href="http://www.async.com.br/projects/kiwi/" rel="nofollow">Kiwi</a> but found it a bit lacking, especially with using the Gazpacho Glade-replacement.</p>
<p>Are there any other nice desktop Python MVC frameworks? I'm one of the few (it seems) to not want a webapp.</p>
| 2 | 2008-11-22T04:26:23Z | 310,951 | <p>"mvc" titled app:</p>
<p><a href="http://sourceforge.net/projects/pygtkmvc/" rel="nofollow">http://sourceforge.net/projects/pygtkmvc/</a></p>
<p>"avc" titled app:</p>
<p><a href="http://avc.inrim.it/html/" rel="nofollow">http://avc.inrim.it/html/</a></p>
<p>more information:</p>
<p><a href="http://www.pygtk.org/applications.html" rel="nofollow">http://www.pygtk.org/applications.html</a></p>
| 2 | 2008-11-22T06:19:22Z | [
"python",
"model-view-controller",
"gtk"
]
|
Python GTK MVC | 310,856 | <p>I've been looking around for a good MVC framework for Python using PyGTK. I've looked at <a href="http://www.async.com.br/projects/kiwi/" rel="nofollow">Kiwi</a> but found it a bit lacking, especially with using the Gazpacho Glade-replacement.</p>
<p>Are there any other nice desktop Python MVC frameworks? I'm one of the few (it seems) to not want a webapp.</p>
| 2 | 2008-11-22T04:26:23Z | 311,282 | <p>In defense of Kiwi:</p>
<ul>
<li>Kiwi works fine with Glade3 instead of Gazpacho. (who forced you to use Gazpacho?)</li>
<li>Kiwi is my first dependency for <em>any</em> PyGTK application commercial or open source.</li>
<li>Kiwi is very actively maintained.</li>
</ul>
<p>I have generally got to a stage where I think its irresponsible to not use Kiwi in a PyGTK application. Perhaps you can tell us what you found "lacking" so we can improve the framework. #kiwi on irc.gimp.net (or the Kiwi mailing list).</p>
| 3 | 2008-11-22T12:25:32Z | [
"python",
"model-view-controller",
"gtk"
]
|
Python GTK MVC | 310,856 | <p>I've been looking around for a good MVC framework for Python using PyGTK. I've looked at <a href="http://www.async.com.br/projects/kiwi/" rel="nofollow">Kiwi</a> but found it a bit lacking, especially with using the Gazpacho Glade-replacement.</p>
<p>Are there any other nice desktop Python MVC frameworks? I'm one of the few (it seems) to not want a webapp.</p>
| 2 | 2008-11-22T04:26:23Z | 381,700 | <p>PureMVC</p>
<p><a href="http://trac.puremvc.org/PureMVC_Python" rel="nofollow">http://trac.puremvc.org/PureMVC_Python</a></p>
| 0 | 2008-12-19T17:58:56Z | [
"python",
"model-view-controller",
"gtk"
]
|
Any DAL/ORM on GAE? | 310,890 | <p>Is there any Database Abstraction Layer (DAL) or Object Relational Mapper (ORM) that works on Google App Engine (GAE), and on normal relational databases (RDBS), other than <a href="http://www.web2py.com" rel="nofollow">web2py</a>'s?</p>
<p>If not, is anybody working on porting one of the existing DAL/ORM to GAE?</p>
| 3 | 2008-11-22T05:01:53Z | 395,565 | <p>Currently, it looks like SQLAlchemy is working on it, but it's incomplete / unfinished. Good luck!</p>
| 0 | 2008-12-27T23:07:53Z | [
"python",
"google-app-engine",
"orm",
"rdbms",
"data-access-layer"
]
|
Any DAL/ORM on GAE? | 310,890 | <p>Is there any Database Abstraction Layer (DAL) or Object Relational Mapper (ORM) that works on Google App Engine (GAE), and on normal relational databases (RDBS), other than <a href="http://www.web2py.com" rel="nofollow">web2py</a>'s?</p>
<p>If not, is anybody working on porting one of the existing DAL/ORM to GAE?</p>
| 3 | 2008-11-22T05:01:53Z | 514,099 | <p>There is an ORM for Google App Engine. There are some differences between it and SQLAlchemy, but looks like it works. Check this page: <a href="http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html</a></p>
| 3 | 2009-02-05T00:59:21Z | [
"python",
"google-app-engine",
"orm",
"rdbms",
"data-access-layer"
]
|
Any DAL/ORM on GAE? | 310,890 | <p>Is there any Database Abstraction Layer (DAL) or Object Relational Mapper (ORM) that works on Google App Engine (GAE), and on normal relational databases (RDBS), other than <a href="http://www.web2py.com" rel="nofollow">web2py</a>'s?</p>
<p>If not, is anybody working on porting one of the existing DAL/ORM to GAE?</p>
| 3 | 2008-11-22T05:01:53Z | 671,195 | <p>Web2Py has a DAL that is compatible to GAE. In fact, the whole framework can be deployed to GAE: <a href="http://mdp.cti.depaul.edu/examples/default/index" rel="nofollow">http://mdp.cti.depaul.edu/examples/default/index</a></p>
| 2 | 2009-03-22T15:47:54Z | [
"python",
"google-app-engine",
"orm",
"rdbms",
"data-access-layer"
]
|
Cleaning form data in Django | 310,931 | <p>How can i clean and modify data from a form in django. I would like to define it on a per field basis for each model, much like using ModelForms.</p>
<p>What I want to achieve is automatically remove leading and trailing spaces from defined fields, or turn a title (from one field) into a slug (which would be another field).</p>
| 7 | 2008-11-22T05:44:09Z | 310,968 | <p>You can define clean_FIELD_NAME() methods which can validate and alter data, as documented here: <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation">http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation</a></p>
| 12 | 2008-11-22T06:42:22Z | [
"python",
"django",
"forms",
"slug"
]
|
How do I edit and delete data in Django? | 311,188 | <p>I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), <b>EDIT</b> it and save it back to the DB. Secondly how do I <b>DELETE</b> the data that's in the DB? i.e. search, select and then delete!</p>
<p>Please show me an example of the code I need to write on my <code>view.py</code> and <code>urls.py</code> for perform this task.</p>
| 4 | 2008-11-22T10:28:56Z | 311,191 | <p>Say you have a model Employee. To edit an entry with primary key emp_id you do:</p>
<pre><code>emp = Employee.objects.get(pk = emp_id)
emp.name = 'Somename'
emp.save()
</code></pre>
<p>to delete it just do:</p>
<pre><code>emp.delete()
</code></pre>
<p>so a full view would be:</p>
<pre><code>def update(request, id):
emp = Employee.objects.get(pk = id)
#you can do this for as many fields as you like
#here I asume you had a form with input like <input type="text" name="name"/>
#so it's basically like that for all form fields
emp.name = request.POST.get('name')
emp.save()
return HttpResponse('updated')
def delete(request, id):
emp = Employee.objects.get(pk = id)
emp.delete()
return HttpResponse('deleted')
</code></pre>
<p>In urls.py you'd need two entries like this:</p>
<pre><code>(r'^delete/(\d+)/$','myproject.myapp.views.delete'),
(r'^update/(\d+)/$','myproject.myapp.views.update'),
</code></pre>
<p>I suggest you take a look at the <a href="http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs">docs</a></p>
| 17 | 2008-11-22T10:36:04Z | [
"python",
"django",
"editing"
]
|
How do I edit and delete data in Django? | 311,188 | <p>I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), <b>EDIT</b> it and save it back to the DB. Secondly how do I <b>DELETE</b> the data that's in the DB? i.e. search, select and then delete!</p>
<p>Please show me an example of the code I need to write on my <code>view.py</code> and <code>urls.py</code> for perform this task.</p>
| 4 | 2008-11-22T10:28:56Z | 311,345 | <p>Read the following: <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin" rel="nofollow">The Django admin site</a>. Then revise your question with specific details.</p>
| -2 | 2008-11-22T13:32:44Z | [
"python",
"django",
"editing"
]
|
Modern, high performance bloom filter in Python? | 311,202 | <p>I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). </p>
<p><a href="http://www.imperialviolet.org/pybloom.html">Pybloom</a> is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has <a href="http://bitworking.org/news/380/bloom-filter-resources">an implementation</a>. </p>
<p>Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.</p>
<p>Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?</p>
| 41 | 2008-11-22T10:53:57Z | 311,360 | <p>Look at the <a href="http://www.python.org/doc/2.5.2/lib/module-array.html" rel="nofollow">array</a> module.</p>
<pre><code>class Bit( object ):
def __init__( self, size ):
self.bits= array.array('B',[0 for i in range((size+7)//8)] )
def set( self, bit ):
b= self.bits[bit//8]
self.bits[bit//8] = b | 1 << (bit % 8)
def get( self, bit ):
b= self.bits[bit//8]
return (b >> (bit % 8)) & 1
</code></pre>
<p>FWIW, all of the <code>//8</code> and <code>% 8</code> operations can be replaced with <code>>>3</code> and <code>&0x07</code>. This <em>may</em> lead to slightly better speed at the risk of some obscurity.</p>
<p>Also, changing <code>'B'</code> and <code>8</code> to <code>'L'</code> and <code>32</code> should be faster on most hardware. [Changing to <code>'H'</code> and 16 might be faster on some hardware, but it's doubtful.]</p>
| 6 | 2008-11-22T13:51:25Z | [
"python",
"jython",
"bloom-filter"
]
|
Modern, high performance bloom filter in Python? | 311,202 | <p>I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). </p>
<p><a href="http://www.imperialviolet.org/pybloom.html">Pybloom</a> is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has <a href="http://bitworking.org/news/380/bloom-filter-resources">an implementation</a>. </p>
<p>Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.</p>
<p>Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?</p>
| 41 | 2008-11-22T10:53:57Z | 311,907 | <p>I recently went down this path as well; though it sounds like my application was slightly different. I was interested in approximating set operations on a large number of strings. </p>
<p>You do make the key observation that a <strong>fast</strong> bit vector is required. Depending on what you want to put in your bloom filter, you may also need to give some thought to the speed of the hashing algorithm(s) used. You might find this <a href="http://www.partow.net/programming/hashfunctions/index.html">library</a> useful. You may also want to tinker with the random number technique used below that only hashes your key a single time.</p>
<p>In terms of non-Java bit array implementations:</p>
<ul>
<li>Boost has <a href="http://www.boost.org/doc/libs/1_37_0/libs/dynamic_bitset/dynamic_bitset.html">dynamic_bitset</a></li>
<li>Java has the built in <a href="http://java.sun.com/javase/6/docs/api/java/util/BitSet.html">BitSet</a></li>
</ul>
<p>I built my bloom filter using <a href="http://cobweb.ecn.purdue.edu/~kak/dist/">BitVector</a>. I spent some time profiling and optimizing the library and contributing back my patches to Avi. Go to that BitVector link and scroll down to acknowledgments in v1.5 to see details. In the end, I realized that performance was not a goal of this project and decided against using it. </p>
<p>Here's some code I had lying around. I may put this up on google code at python-bloom. Suggestions welcome.</p>
<pre><code>from BitVector import BitVector
from random import Random
# get hashes from http://www.partow.net/programming/hashfunctions/index.html
from hashes import RSHash, JSHash, PJWHash, ELFHash, DJBHash
#
# ryan.a.cox@gmail.com / www.asciiarmor.com
#
# copyright (c) 2008, ryan cox
# all rights reserved
# BSD license: http://www.opensource.org/licenses/bsd-license.php
#
class BloomFilter(object):
def __init__(self, n=None, m=None, k=None, p=None, bits=None ):
self.m = m
if k > 4 or k < 1:
raise Exception('Must specify value of k between 1 and 4')
self.k = k
if bits:
self.bits = bits
else:
self.bits = BitVector( size=m )
self.rand = Random()
self.hashes = []
self.hashes.append(RSHash)
self.hashes.append(JSHash)
self.hashes.append(PJWHash)
self.hashes.append(DJBHash)
# switch between hashing techniques
self._indexes = self._rand_indexes
#self._indexes = self._hash_indexes
def __contains__(self, key):
for i in self._indexes(key):
if not self.bits[i]:
return False
return True
def add(self, key):
dupe = True
bits = []
for i in self._indexes(key):
if dupe and not self.bits[i]:
dupe = False
self.bits[i] = 1
bits.append(i)
return dupe
def __and__(self, filter):
if (self.k != filter.k) or (self.m != filter.m):
raise Exception('Must use bloom filters created with equal k / m paramters for bitwise AND')
return BloomFilter(m=self.m,k=self.k,bits=(self.bits & filter.bits))
def __or__(self, filter):
if (self.k != filter.k) or (self.m != filter.m):
raise Exception('Must use bloom filters created with equal k / m paramters for bitwise OR')
return BloomFilter(m=self.m,k=self.k,bits=(self.bits | filter.bits))
def _hash_indexes(self,key):
ret = []
for i in range(self.k):
ret.append(self.hashes[i](key) % self.m)
return ret
def _rand_indexes(self,key):
self.rand.seed(hash(key))
ret = []
for i in range(self.k):
ret.append(self.rand.randint(0,self.m-1))
return ret
if __name__ == '__main__':
e = BloomFilter(m=100, k=4)
e.add('one')
e.add('two')
e.add('three')
e.add('four')
e.add('five')
f = BloomFilter(m=100, k=4)
f.add('three')
f.add('four')
f.add('five')
f.add('six')
f.add('seven')
f.add('eight')
f.add('nine')
f.add("ten")
# test check for dupe on add
assert not f.add('eleven')
assert f.add('eleven')
# test membership operations
assert 'ten' in f
assert 'one' in e
assert 'ten' not in e
assert 'one' not in f
# test set based operations
union = f | e
intersection = f & e
assert 'ten' in union
assert 'one' in union
assert 'three' in intersection
assert 'ten' not in intersection
assert 'one' not in intersection
</code></pre>
<p>Also, in my case I found it useful to have a faster count_bits function for BitVector. Drop this code into BitVector 1.5 and it should give you a more performant bit counting method:</p>
<pre><code>def fast_count_bits( self, v ):
bits = (
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 )
return bits[v & 0xff] + bits[(v >> 8) & 0xff] + bits[(v >> 16) & 0xff] + bits[v >> 24]
</code></pre>
| 25 | 2008-11-22T23:35:59Z | [
"python",
"jython",
"bloom-filter"
]
|
Modern, high performance bloom filter in Python? | 311,202 | <p>I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). </p>
<p><a href="http://www.imperialviolet.org/pybloom.html">Pybloom</a> is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has <a href="http://bitworking.org/news/380/bloom-filter-resources">an implementation</a>. </p>
<p>Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.</p>
<p>Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?</p>
| 41 | 2008-11-22T10:53:57Z | 3,390,002 | <p>Eventually I found <a href="http://github.com/axiak/pybloomfiltermmap">pybloomfiltermap</a>. I haven't used it, but it looks like it'd fit the bill. </p>
| 8 | 2010-08-02T17:00:09Z | [
"python",
"jython",
"bloom-filter"
]
|
Modern, high performance bloom filter in Python? | 311,202 | <p>I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). </p>
<p><a href="http://www.imperialviolet.org/pybloom.html">Pybloom</a> is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has <a href="http://bitworking.org/news/380/bloom-filter-resources">an implementation</a>. </p>
<p>Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.</p>
<p>Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?</p>
| 41 | 2008-11-22T10:53:57Z | 3,400,221 | <p>I am keenly interested in Bloom filters variants, their performance and understand their use-cases.
There are so many well-cited research work on Bloom filter variants( including ones published in top-notch conferences like SIGCOMM,SIGMETRICS) yet I dont think their presence is strong in mainstream language libraries. Why do you think that's the case?</p>
<p>While my interest is language-agnostic,I wanted to share an article I wrote on Bloom filter variants, and applications of Bloom filter. </p>
<p><a href="http://appolo85.wordpress.com/2010/08/03/bloom-filter/" rel="nofollow">http://appolo85.wordpress.com/2010/08/03/bloom-filter/</a></p>
<p>I would love to learn more about their use-cases of the Bloom filter variants, and their design/implementation, and libraries in other languages. </p>
<p>Do you think that most of the publications, and ( code?) on Bloom filters variants , only serve to increment the published paper count of a PhD graduate?<br>
Or is it that most people do not want to mess with a production-ready standard bloom filter implementation that "works just fine" :D </p>
| 0 | 2010-08-03T19:45:53Z | [
"python",
"jython",
"bloom-filter"
]
|
Modern, high performance bloom filter in Python? | 311,202 | <p>I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). </p>
<p><a href="http://www.imperialviolet.org/pybloom.html">Pybloom</a> is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has <a href="http://bitworking.org/news/380/bloom-filter-resources">an implementation</a>. </p>
<p>Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.</p>
<p>Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?</p>
| 41 | 2008-11-22T10:53:57Z | 4,125,080 | <p>In reaction to Parand, saying "common practice seems to be using something like SHA1 and split up the bits to form multiple hashes", while that may be true in the sense that it's common practice (PyBloom also uses it), it still doesn't mean it's the right thing to do ;-)</p>
<p>For a Bloom filter, the only requirement a hash function has is that its output space must be uniformly distributed given the expected input. While a cryptographic hash certainly fulfils this requirement, it's also a little bit like shooting a fly with a bazooka.</p>
<p>Instead try the <a href="http://www.isthe.com/chongo/tech/comp/fnv/" rel="nofollow">FNV Hash</a> which uses just one XOR and one multiplication per input byte, which I estimate is a few hundred times faster than SHA1 :)</p>
<p>The FNV hash is not cryptographically secure, but you don't need it to be. It has slightly <a href="https://web.archive.org/web/20130617200738/http://bretm.home.comcast.net/~bretm/hash/6.html" rel="nofollow">imperfect avalanche behaviour</a>, but you're not using it for integrity checking either.</p>
<p>About uniformity, note that the second link only did a Chi-square test for the 32-bit FNV hash. It's better to use more bits and the FNV-1 variant, which swaps the XOR and the MUL steps for better bit-dispersion. For a Bloom Filter, there's a few more catches, such as mapping the output uniformly to the index range of the bit-array. If possible, I'd say round up the size of the bit-array to the nearest power of 2 and adjust <em>k</em> accordingly. That way you get better accuracy and you can use simple XOR-folding to map the range.</p>
<p>Additionally, here's a reference explaining why you don't want SHA1 (or any cryptographic hash) when you need <a href="https://web.archive.org/web/20120722074824/http://bretm.home.comcast.net/~bretm/hash/9.html" rel="nofollow">a general purpose hash</a>.</p>
| 22 | 2010-11-08T15:10:21Z | [
"python",
"jython",
"bloom-filter"
]
|
Modern, high performance bloom filter in Python? | 311,202 | <p>I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). </p>
<p><a href="http://www.imperialviolet.org/pybloom.html">Pybloom</a> is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has <a href="http://bitworking.org/news/380/bloom-filter-resources">an implementation</a>. </p>
<p>Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.</p>
<p>Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?</p>
| 41 | 2008-11-22T10:53:57Z | 7,912,153 | <p>You can try with <code>it.unimi.dsi.util.BloomFilter</code> of <a href="http://dsiutils.di.unimi.it/" rel="nofollow">The DSI Utilities</a>.</p>
| 0 | 2011-10-27T05:53:23Z | [
"python",
"jython",
"bloom-filter"
]
|
Modern, high performance bloom filter in Python? | 311,202 | <p>I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). </p>
<p><a href="http://www.imperialviolet.org/pybloom.html">Pybloom</a> is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has <a href="http://bitworking.org/news/380/bloom-filter-resources">an implementation</a>. </p>
<p>Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.</p>
<p>Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?</p>
| 41 | 2008-11-22T10:53:57Z | 12,060,876 | <p>I've put up a python bloom filter implementation at <a href="http://stromberg.dnsalias.org/~strombrg/drs-bloom-filter/" rel="nofollow">http://stromberg.dnsalias.org/~strombrg/drs-bloom-filter/</a></p>
<p>It's in pure python, has good hash functions, good automated tests, a selection of backends (disk, array, mmap, more) and more intuitive arguments to the <code>__init__</code> method, so you can specify an ideal number of elements and desired maximum error rate, instead of somewhat ethereal, datastructure-specific tunables.</p>
| 2 | 2012-08-21T18:27:47Z | [
"python",
"jython",
"bloom-filter"
]
|
Admin generic inlines for multi-table subclassed models broken --- any alternatives? | 311,300 | <p>Here's what I'm trying to do, and failing...</p>
<p>I have a File model which has a generic-relation to other objects:</p>
<pre><code>class File(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
file = models.FileField(upload_to='files/%Y/%m/%d')
# etc....
</code></pre>
<p>I also want to have a sub-class of File to deal with the specific case of images to be displayed in-page, rather than downloaded:</p>
<pre><code>class Image(File):
file = models.ImageField(upload_to='files/%Y/%m/%d')
</code></pre>
<p>All of the above works fine, including generic inlines of the File model, until I want to use a generic-inline of the Image model --- the save process fails to create the base class instance and so raises an error stating that the Image.file_ptr (the 'secret' foreign key to the base class) cannot be None.</p>
<p>So, basically, generic inlines do not properly support multi-table inheritance at the moment.</p>
<p>It's quite likely that I'm making this more complicated than it need be, so can anyone suggest either a fix for this problem, or a better way of achieving the same end?</p>
<p>Please let me know if you need further clarification.</p>
| 2 | 2008-11-22T12:43:53Z | 311,344 | <p>Inheritance can be implemented two ways in a relational model.</p>
<p>A subclass can be a new table with all the same columns as the superclass repeated. This works well when you have an abstract superclass or subclass features that override the superclass.</p>
<p>A subclass can be just the unique columns with a join to the superclass table. This works well when you have a concrete superclass.</p>
<p>In your case, it looks you might have the following.</p>
<pre><code>class FileFacts( models.Model ):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
class DownloadFile( models.Model ):
facts = models.ForeignKey( FileFacts )
file = models.FileField(upload_to='files/%Y/%m/%d')
class InlineImage( models.Model ):
facts = models.ForeignKey( FileFacts )
file = models.ImageField(upload_to='files/%Y/%m/%d')
</code></pre>
<p>This is my preference for handling a subclass-like model.</p>
| 0 | 2008-11-22T13:30:28Z | [
"python",
"django",
"django-models",
"django-admin"
]
|
How to indent Python list-comprehensions? | 311,588 | <p>List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
</code></pre>
| 31 | 2008-11-22T18:08:18Z | 311,590 | <p>How about:</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20)
if (x.type == "post" and x.deleted is not False)]
</code></pre>
<p>Generally, long lines can be avoided by pre-computing subexpressions into variables, which might add a minuscule performance cost:</p>
<pre><code>query_ids = self.db.query(schema.allPostsUuid).execute(timeout = 20)
allUuids = [x.id for x in query_ids
if (x.type == "post" and x.deleted is not False)]
</code></pre>
<p>By the way, isn't '<code>is not False</code>' kind-of superfluous ? Are you worried about differentiating between None and False ? Because otherwise, it suffices to leave the condition as only: i<code>f (x.type == "post" and x.deleted)</code></p>
| 1 | 2008-11-22T18:10:33Z | [
"python",
"coding-style"
]
|
How to indent Python list-comprehensions? | 311,588 | <p>List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
</code></pre>
| 31 | 2008-11-22T18:08:18Z | 311,597 | <p>For me that's too much. Maybe it's just a terrible example, since "type" and "deleted" would clearly be part of the db query.</p>
<p>I tend to think that if a list comprehension spans multiple lines it probably shouldn't be a list comprehension. Having said that, I usually just split the thing at "if" like other people have and will answer here.</p>
| 5 | 2008-11-22T18:15:40Z | [
"python",
"coding-style"
]
|
How to indent Python list-comprehensions? | 311,588 | <p>List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
</code></pre>
| 31 | 2008-11-22T18:08:18Z | 311,604 | <p>It depends on how long they are. I tend to structure them like so:</p>
<pre><code>[x.id for x
in self.db.query(schema.allPostsUuid).execute(timeout=20)
if x.type == 'post'
and x.deleted is not False
and ...
and ...]
</code></pre>
<p>That way every expression has its own line.</p>
<p>If any line becomes too big I like to extract it out in a lambda or expression:</p>
<pre><code>transform = lambda x: x.id
results = self.db.query(schema.allPostsUuid).execute(timeout=20)
condition = lambda x: x.deleted is not False and ... and ...
[transform(x) for x in results if condition(x)]
</code></pre>
<p>And then if a lambda becomes too long it gets promoted to a function.</p>
| 38 | 2008-11-22T18:19:41Z | [
"python",
"coding-style"
]
|
How to indent Python list-comprehensions? | 311,588 | <p>List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
</code></pre>
| 31 | 2008-11-22T18:08:18Z | 311,675 | <p>Where I work, our coding guidelines would have us do something like this:</p>
<pre><code>all_posts_uuid_query = self.db.query(schema.allPostsUuid)
all_posts_uuid_list = all_posts_uuid_query.execute(timeout=20)
all_uuid_list = [
x.id
for x in all_posts_uuid_list
if (
x.type == "post"
and
not x.deleted # <-- if you don't care about NULLs / None
)
]
</code></pre>
| 27 | 2008-11-22T19:29:24Z | [
"python",
"coding-style"
]
|
How to indent Python list-comprehensions? | 311,588 | <p>List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
</code></pre>
| 31 | 2008-11-22T18:08:18Z | 311,678 | <pre><code>allUuids = [x.id
for x in self.db.query(schema.allPostsUuid).execute(timeout = 20)
if x.type == "post" and x.deleted is not False]
</code></pre>
| 5 | 2008-11-22T19:32:12Z | [
"python",
"coding-style"
]
|
How to indent Python list-comprehensions? | 311,588 | <p>List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
</code></pre>
| 31 | 2008-11-22T18:08:18Z | 311,680 | <p><strong>You should not use a list comprehension for that</strong>.</p>
<p>List comprehensions are an awesome feature, but they are meant to be shortcuts, not regular code.</p>
<p>For such a long snippet, you should use ordinary blocs :</p>
<pre><code>allUuids = []
for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) :
if x.type == "post" and x.deleted is not False :
allUuids.append(x.id)
</code></pre>
<p>Exactly the same behavior, much more readable. Guido would be proud of you :-)</p>
| 6 | 2008-11-22T19:36:18Z | [
"python",
"coding-style"
]
|
How to indent Python list-comprehensions? | 311,588 | <p>List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
</code></pre>
| 31 | 2008-11-22T18:08:18Z | 34,314,371 | <p>If you're set on a comprehension <a href="http://stackoverflow.com/a/311604/1887870">orestis's answer</a> is good.</p>
<p>For more complex comprehensions like that I'd suggest using a generator with <code>yield</code>:</p>
<pre><code>allUuids = list(self.get_all_uuids())
def get_all_uuids(self):
for x in self.db.query(schema.allPostsUuid).execute(timeout = 20):
if x.type == "post" and x.deleted is not False:
yield x.id
</code></pre>
| 0 | 2015-12-16T14:18:51Z | [
"python",
"coding-style"
]
|
python as a "batch" script (i.e. run commands from python) | 311,601 | <p>I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.</p>
<p>how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time. </p>
<p>So, just running a program and printing the output won't suffice. The program has to takeover the script's input/output, pretty mcuh like running the command from a .bat file. </p>
<p>I tried os.execl but it keeps telling me "invalid arguments", also, it doesn't find the program name (doesn't search the PATH variable); I have to give it the full path ..?!</p>
<p>basically, in a batch script I can write:
unison profile</p>
<p>how can I achieve the same effect in python?</p>
<p>EDIT:</p>
<p>I found out it can be done with <code>os.system( ... )</code> and since I cannot accept my own answer, I'm closing the question.</p>
<hr>
<p>EDIT: this was supposed to be a comment, but when I posted it I didn't have much points.</p>
<p>Thanks Claudiu, that's pretty much what I want, except for a little thing: I want the function to end when the program exits, but when I try it on unison, it doesn't return control to the python script, but to the windows command line environment</p>
<pre><code>>>> os.execlp("unison")
C:\>Usage: unison [options]
or unison root1 root2 [options]
or unison profilename [options]
For a list of options, type "unison -help".
For a tutorial on basic usage, type "unison -doc tutorial".
For other documentation, type "unison -doc topics".
C:\>
C:\>
C:\>
</code></pre>
<p>how to get around this?</p>
| 4 | 2008-11-22T18:18:58Z | 311,613 | <p>You should create a new processess using the <a href="http://www.python.org/doc/2.5.2/lib/module-subprocess.html">subprocess module</a>.</p>
<p>I'm not fluent in windows processes but its Popen function is cross-platform, and should be preffered to OS specific solutions.</p>
<p>EDIT: I maintain that you should prefer the Subprocess module to os.* OS specific functions, it is cross-platform and more pythonic (just google it). You can wait for the result easily, and <em>cleanly</em>:</p>
<pre><code>import os
import subprocess
unison = os.path.join(os.path.curdir, "unison")
p = subprocess.Popen(unison)
p.wait()
</code></pre>
| 17 | 2008-11-22T18:25:47Z | [
"python",
"scripting",
"batch-file"
]
|
python as a "batch" script (i.e. run commands from python) | 311,601 | <p>I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.</p>
<p>how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time. </p>
<p>So, just running a program and printing the output won't suffice. The program has to takeover the script's input/output, pretty mcuh like running the command from a .bat file. </p>
<p>I tried os.execl but it keeps telling me "invalid arguments", also, it doesn't find the program name (doesn't search the PATH variable); I have to give it the full path ..?!</p>
<p>basically, in a batch script I can write:
unison profile</p>
<p>how can I achieve the same effect in python?</p>
<p>EDIT:</p>
<p>I found out it can be done with <code>os.system( ... )</code> and since I cannot accept my own answer, I'm closing the question.</p>
<hr>
<p>EDIT: this was supposed to be a comment, but when I posted it I didn't have much points.</p>
<p>Thanks Claudiu, that's pretty much what I want, except for a little thing: I want the function to end when the program exits, but when I try it on unison, it doesn't return control to the python script, but to the windows command line environment</p>
<pre><code>>>> os.execlp("unison")
C:\>Usage: unison [options]
or unison root1 root2 [options]
or unison profilename [options]
For a list of options, type "unison -help".
For a tutorial on basic usage, type "unison -doc tutorial".
For other documentation, type "unison -doc topics".
C:\>
C:\>
C:\>
</code></pre>
<p>how to get around this?</p>
| 4 | 2008-11-22T18:18:58Z | 311,616 | <p><code>os.execlp</code> should work. This will search your path for the command. Don't give it any args if they're not necessary:</p>
<pre><code>>>> import os
>>> os.execlp("cmd")
D:\Documents and Settings\Claudiu>Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
D:\Documents and Settings\Claudiu>
</code></pre>
| 2 | 2008-11-22T18:26:42Z | [
"python",
"scripting",
"batch-file"
]
|
python as a "batch" script (i.e. run commands from python) | 311,601 | <p>I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.</p>
<p>how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time. </p>
<p>So, just running a program and printing the output won't suffice. The program has to takeover the script's input/output, pretty mcuh like running the command from a .bat file. </p>
<p>I tried os.execl but it keeps telling me "invalid arguments", also, it doesn't find the program name (doesn't search the PATH variable); I have to give it the full path ..?!</p>
<p>basically, in a batch script I can write:
unison profile</p>
<p>how can I achieve the same effect in python?</p>
<p>EDIT:</p>
<p>I found out it can be done with <code>os.system( ... )</code> and since I cannot accept my own answer, I'm closing the question.</p>
<hr>
<p>EDIT: this was supposed to be a comment, but when I posted it I didn't have much points.</p>
<p>Thanks Claudiu, that's pretty much what I want, except for a little thing: I want the function to end when the program exits, but when I try it on unison, it doesn't return control to the python script, but to the windows command line environment</p>
<pre><code>>>> os.execlp("unison")
C:\>Usage: unison [options]
or unison root1 root2 [options]
or unison profilename [options]
For a list of options, type "unison -help".
For a tutorial on basic usage, type "unison -doc tutorial".
For other documentation, type "unison -doc topics".
C:\>
C:\>
C:\>
</code></pre>
<p>how to get around this?</p>
| 4 | 2008-11-22T18:18:58Z | 311,623 | <pre><code>import subprocess
proc = subprocess.Popen(['unison', 'profile'], stderr=subprocess.PIPE,
stdout=subprocess.PIPE, stdin=subprocess.PIPE)
proc.stdin.write('user input')
print proc.stdout.read()
</code></pre>
<p>This should help you get started. Please edit your question with more information if you want a more detailed answer!</p>
| 4 | 2008-11-22T18:31:57Z | [
"python",
"scripting",
"batch-file"
]
|
python as a "batch" script (i.e. run commands from python) | 311,601 | <p>I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.</p>
<p>how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time. </p>
<p>So, just running a program and printing the output won't suffice. The program has to takeover the script's input/output, pretty mcuh like running the command from a .bat file. </p>
<p>I tried os.execl but it keeps telling me "invalid arguments", also, it doesn't find the program name (doesn't search the PATH variable); I have to give it the full path ..?!</p>
<p>basically, in a batch script I can write:
unison profile</p>
<p>how can I achieve the same effect in python?</p>
<p>EDIT:</p>
<p>I found out it can be done with <code>os.system( ... )</code> and since I cannot accept my own answer, I'm closing the question.</p>
<hr>
<p>EDIT: this was supposed to be a comment, but when I posted it I didn't have much points.</p>
<p>Thanks Claudiu, that's pretty much what I want, except for a little thing: I want the function to end when the program exits, but when I try it on unison, it doesn't return control to the python script, but to the windows command line environment</p>
<pre><code>>>> os.execlp("unison")
C:\>Usage: unison [options]
or unison root1 root2 [options]
or unison profilename [options]
For a list of options, type "unison -help".
For a tutorial on basic usage, type "unison -doc tutorial".
For other documentation, type "unison -doc topics".
C:\>
C:\>
C:\>
</code></pre>
<p>how to get around this?</p>
| 4 | 2008-11-22T18:18:58Z | 311,646 | <p>I found out that os.system does what I want, </p>
<p>Thanks for all that tried to help.</p>
<pre><code>os.system("dir")
</code></pre>
<p>runs the command just as if it was run from a batch file</p>
| 5 | 2008-11-22T18:57:17Z | [
"python",
"scripting",
"batch-file"
]
|
Accidental overwrite of OSX Python system framework | 311,621 | <p>I got ahead of myself and downloaded and installed the OSX Python 2.6 package from www.python.org/download/ on my OSX 10.5.5 Intel Mac and installed the full package contents. Only after this did I come across <a href="http://wiki.python.org/moin/MacPython/Leopard" rel="nofollow">http://wiki.python.org/moin/MacPython/Leopard</a> stating that you should do a partial install of the package to avoid interfering with the system install.</p>
<p>I'm afraid I've already overwritten the system framework through that installer and I remember reading somewhere after discovering this that I'd lose certain elements included in the OSX system install and not Python distributions.</p>
<p>Is there any way to reverse this or restore anything I may have lost? What exactly have I lost and is it going to be a problem? </p>
| 2 | 2008-11-22T18:30:35Z | 311,643 | <p>Restore from a recent Time Machine backup or somehow from DVD?</p>
| -1 | 2008-11-22T18:52:07Z | [
"python",
"osx",
"frameworks",
"osx-leopard"
]
|
Accidental overwrite of OSX Python system framework | 311,621 | <p>I got ahead of myself and downloaded and installed the OSX Python 2.6 package from www.python.org/download/ on my OSX 10.5.5 Intel Mac and installed the full package contents. Only after this did I come across <a href="http://wiki.python.org/moin/MacPython/Leopard" rel="nofollow">http://wiki.python.org/moin/MacPython/Leopard</a> stating that you should do a partial install of the package to avoid interfering with the system install.</p>
<p>I'm afraid I've already overwritten the system framework through that installer and I remember reading somewhere after discovering this that I'd lose certain elements included in the OSX system install and not Python distributions.</p>
<p>Is there any way to reverse this or restore anything I may have lost? What exactly have I lost and is it going to be a problem? </p>
| 2 | 2008-11-22T18:30:35Z | 311,682 | <p>You may have overwritten the system framework but it is more likely that you just overwrote the symlinks in <code>/usr/bin</code> to point to the new version. Try going to <code>/usr/bin</code> and seeing (with something like <code>ls -alsh</code>) where the <code>python</code> symlink points to. It may be <code>python2.6</code> or <code>3.0</code>, which is in turn a ln to <code>/System/Library/Frameworks/Python.framework/Versions ...</code> etc. First try resetting the python symlink to the stable or expected version, ie, <code>sudo ln -s /usr/bin/python2.5 python</code> (from the <code>/usr/bin</code> dir.)</p>
| 5 | 2008-11-22T19:37:33Z | [
"python",
"osx",
"frameworks",
"osx-leopard"
]
|
Accidental overwrite of OSX Python system framework | 311,621 | <p>I got ahead of myself and downloaded and installed the OSX Python 2.6 package from www.python.org/download/ on my OSX 10.5.5 Intel Mac and installed the full package contents. Only after this did I come across <a href="http://wiki.python.org/moin/MacPython/Leopard" rel="nofollow">http://wiki.python.org/moin/MacPython/Leopard</a> stating that you should do a partial install of the package to avoid interfering with the system install.</p>
<p>I'm afraid I've already overwritten the system framework through that installer and I remember reading somewhere after discovering this that I'd lose certain elements included in the OSX system install and not Python distributions.</p>
<p>Is there any way to reverse this or restore anything I may have lost? What exactly have I lost and is it going to be a problem? </p>
| 2 | 2008-11-22T18:30:35Z | 1,093,371 | <p>I just ran into the same thing myself. I did find that the MacPython installer modified my search $PATH and added '/Library/Frameworks/Python.framework/Versions/Current/bin' which caused the python executable there to be found before the one in '/usr/bin'.</p>
<p>Hope this helps anyone else!</p>
| 0 | 2009-07-07T16:28:31Z | [
"python",
"osx",
"frameworks",
"osx-leopard"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 311,635 | <p>You need to convert the date time object to a string.</p>
<p>The following code worked for me:</p>
<pre><code>import datetime
collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
print collection
</code></pre>
<p>Let me know if you need any more help.</p>
| 2 | 2008-11-22T18:45:00Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 311,636 | <p>You may want to append it as a string?</p>
<pre><code>import datetime
mylist = []
today = str(datetime.date.today())
mylist.append(today)
print mylist
</code></pre>
| 1 | 2008-11-22T18:45:26Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 311,637 | <p>You can do:</p>
<pre><code>mylist.append(str(today))
</code></pre>
| 1 | 2008-11-22T18:46:05Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 311,645 | <p>Use date.strftime. The formatting arguments are <a href="https://docs.python.org/2/library/time.html#time.strftime">described in the documentation</a>.</p>
<p>This one is what you wanted:</p>
<pre><code>some_date.strftime('%Y-%m-%d')
</code></pre>
<p>This one takes Locale into account. (do this)</p>
<pre><code>some_date.strftime('%c')
</code></pre>
| 60 | 2008-11-22T18:56:08Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 311,655 | <h2>The WHY: dates are objects</h2>
<p>In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings, not timestamps nor anything.</p>
<p>Any object in Python have TWO string representations:</p>
<ul>
<li><p>The regular representation that is used by "print", can be get using the <code>str()</code> function. It is most of the time the most common human readable format and is used to ease display. So <code>str(datetime.datetime(2008, 11, 22, 19, 53, 42))</code> gives you <code>'2008-11-22 19:53:42'</code>. </p></li>
<li><p>The alternative representation that is used to represent the object nature (as a data). It can be get using the <code>repr()</code> function and is handy to know what kind of data your manipulating while you are developing or debugging. <code>repr(datetime.datetime(2008, 11, 22, 19, 53, 42))</code> gives you <code>'datetime.datetime(2008, 11, 22, 19, 53, 42)'</code>.</p></li>
</ul>
<p>What happened is that when you have printed the date using "print", it used <code>str()</code> so you could see a nice date string. But when you have printed <code>mylist</code>, you have printed a list of objects and Python tried to represent the set of data, using <code>repr()</code>.</p>
<h2>The How: what do you want to do with that?</h2>
<p>Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.</p>
<p>When you want to display them, just use <code>str()</code>. In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using <code>str(date)</code>.</p>
<p>One last thing. When you tried to print the dates, you printed <code>mylist</code>. If you want to print a date, you must print the date objects, not their container (the list).</p>
<p>E.G, you want to print all the date in a list :</p>
<pre><code>for date in mylist :
print str(date)
</code></pre>
<p>Note that <strong><em>in that specific case</em></strong>, you can even omit <code>str()</code> because print will use it for you. But it should not become a habit :-)</p>
<h2>Practical case, using your code</h2>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22
# It's better to always use str() because :
print "This is a new day : ", mylist[0] # will work
This is a new day : 2008-11-22
print "This is a new day : " + mylist[0] # will crash
cannot concatenate 'str' and 'datetime.date' objects
print "This is a new day : " + str(mylist[0])
This is a new day : 2008-11-22
</code></pre>
<h2>Advanced date formatting</h2>
<p>Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the <code>strftime()</code> method.</p>
<p><code>strftime()</code> expects a string pattern explaining how you want to format your date.</p>
<p>E.G : </p>
<pre><code>print today.strftime('We are the %d, %b %Y')
'We are the 22, Nov 2008'
</code></pre>
<p>All the letter after a <code>"%"</code> represent a format for something :</p>
<ul>
<li><code>%d</code> is the day number</li>
<li><code>%m</code> is the month number</li>
<li><code>%b</code> is the month abbreviation</li>
<li><code>%y</code> is the year last two digits</li>
<li><code>%Y</code> is the all year</li>
</ul>
<p>etc</p>
<p><a href="http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior">Have a look at the official documentation</a>, or <a href="http://strftime.org">McCutchen's quick reference</a> you can't know them all.</p>
<p>Since <a href="http://www.python.org/dev/peps/pep-3101/">PEP3101</a>, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in
strftime. So you can do the same as above like this:</p>
<pre><code>print "We are the {:%d, %b %Y}".format(today)
'We are the 22, Nov 2008'
</code></pre>
<p>The advantage of this form is that you can also convert other objects at the same time.</p>
<h2>Localization</h2>
<p>Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)</p>
| 496 | 2008-11-22T19:07:07Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 14,320,620 | <pre><code>import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
</code></pre>
<p><strong>Edit:</strong></p>
<p>After Cees suggestion, I have started using time as well:</p>
<pre><code>import time
print time.strftime("%Y-%m-%d %H:%M")
</code></pre>
| 126 | 2013-01-14T14:46:28Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 18,944,849 | <p>The date, datetime, and time objects all support a strftime(format) method,
to create a string representing the time under the control of an explicit format
string.</p>
<p>Here is a list of the format codes with their directive and meaning. </p>
<pre><code> %a Localeâs abbreviated weekday name.
%A Localeâs full weekday name.
%b Localeâs abbreviated month name.
%B Localeâs full month name.
%c Localeâs appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%f Microsecond as a decimal number [0,999999], zero-padded on the left
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Localeâs equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week)
%x Localeâs appropriate date representation.
%X Localeâs appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%z UTC offset in the form +HHMM or -HHMM.
%Z Time zone name (empty string if the object is naive).
%% A literal '%' character.
</code></pre>
<p>This is what we can do with the datetime and time modules in Python</p>
<pre><code> import time
import datetime
print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: " , datetime.datetime.now()
print "Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")
</code></pre>
<p>That will print out something like this:</p>
<pre><code> Time in seconds since the epoch: 1349271346.46
Current date and time: 2012-10-03 15:35:46.461491
Or like this: 12-10-03-15-35
Current year: 2012
Month of year: October
Week number of the year: 40
Weekday of the week: 3
Day of year: 277
Day of the month : 03
Day of week: Wednesday
</code></pre>
| 58 | 2013-09-22T14:26:14Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 20,066,760 | <p>This is shorter:</p>
<pre><code>>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'
</code></pre>
| 15 | 2013-11-19T08:39:04Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 20,776,958 | <p>Or even </p>
<pre><code>from datetime import datetime, date
"{:%d.%m.%Y}".format(datetime.now())
</code></pre>
<p>Out: '25.12.2013</p>
<p>or</p>
<pre><code>"{} - {:%d.%m.%Y}".format("Today", datetime.now())
</code></pre>
<p>Out: 'Today - 25.12.2013'</p>
<pre><code>"{:%A}".format(date.today())
</code></pre>
<p>Out: 'Wednesday'</p>
<pre><code>'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())
</code></pre>
<p>Out: '__main____2014.06.09__16-56.log'</p>
| 11 | 2013-12-25T21:37:07Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 26,989,550 | <p>Since the <code>print today</code> returns what you want this means that the today object's <code>__str__</code> function returns the string you are looking for. </p>
<p>So you can do <code>mylist.append(today.__str__())</code> as well.</p>
| 0 | 2014-11-18T08:17:00Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 28,263,165 | <p>Simple answer - </p>
<pre><code>datetime.date.today().isoformat()
</code></pre>
| 3 | 2015-02-01T13:23:22Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 29,179,216 | <p>A quick disclaimer for my answer - I've only been learning Python for about 2 weeks, so I am by no means an expert; therefore, my explanation may not be the best and I may use incorrect terminology. Anyway, here it goes.</p>
<p>I noticed in your code that when you declared your variable <code>today = datetime.date.today()</code> you chose to name your variable with the name of a built-in function. </p>
<p>When your next line of code <code>mylist.append(today)</code> appended your list, it appended the entire string <code>datetime.date.today()</code>, which you had previously set as the value of your <code>today</code> variable, rather than just appending <code>today()</code>. </p>
<p>A simple solution, albeit maybe not one most coders would use when working with the datetime module, is to change the name of your variable.</p>
<p>Here's what I tried: </p>
<pre><code>import datetime
mylist = []
present = datetime.date.today()
mylist.append(present)
print present
</code></pre>
<p>and it prints <code>yyyy-mm-dd</code>.</p>
| 0 | 2015-03-21T04:21:22Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 29,600,276 | <p>I hate the idea of importing too many modules for convenience. I would rather work with available module which in this case is <code>datetime</code> rather than calling a new module <code>time</code>.</p>
<p><code>a = datetime.datetime(2015, 04, 01, 11, 23, 22)
a.strftime('%Y-%m-%d %H:%M')
'2015-04-01 11:23'
</code></p>
| 1 | 2015-04-13T07:47:02Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 30,148,084 | <p>You can use <a href="https://github.com/ralphavalon/easy_date" rel="nofollow">easy_date</a> to make it easy:</p>
<pre><code>import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')
</code></pre>
| 0 | 2015-05-10T05:32:55Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 37,902,499 | <p>Here is how to display the date as (year/month/day) :</p>
<pre><code>from datetime import datetime
now = datetime.now()
print '%s/%s/%s' % (now.year, now.month, now.day)
</code></pre>
| 0 | 2016-06-18T23:19:40Z | [
"python",
"datetime",
"date"
]
|
How to print date in a regular format in Python? | 311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print today
</code></pre>
<p>This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How on earth can I get just a simple date like "2008-11-22"?</p>
| 315 | 2008-11-22T18:37:07Z | 39,891,095 | <pre><code># convert date time to regular format.
d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)
# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)
</code></pre>
<blockquote>
<p>OUTPUT</p>
</blockquote>
<pre><code>2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34
</code></pre>
| 2 | 2016-10-06T08:24:34Z | [
"python",
"datetime",
"date"
]
|
Parsing GPS receiver output via regex in Python | 311,763 | <p>I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus.</p>
<p>Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice.</p>
<p>At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold:</p>
<p>$GPRMC,092204.999,<strong>4250.5589,S,14718.5084,E</strong>,1,12,24.4,<strong>89.6</strong>,M,,,0000*1F
$GPRMC,093345.679,<strong>4234.7899,N,11344.2567,W</strong>,3,02,24.5,<strong>1000.23</strong>,M,,,0000*1F
$GPRMC,044584.936,<strong>1276.5539,N,88734.1543,E</strong>,2,04,33.5,<strong>600.323</strong>,M,,,*00
$GPRMC,199304.973,<strong>3248.7780,N,11355.7832,W</strong>,1,06,02.2,<strong>25722.5</strong>,M,,,*00
$GPRMC,066487.954,<strong>4572.0089,S,45572.3345,W</strong>,3,09,15.0,<strong>35000.00</strong>,M,,,*1F</p>
<p>Here is some further explanation of the data:</p>
<blockquote>
<p>"I looks like I'll need five things
out of every line. And bear in mind
that any one of these area's may be
empty. Meaning there will be just two
commas right next to each other. Such
as ',,,' There are two fields that may
be full at any time. Some of them only
have two or three options that they
may be but I don't think I should be
counting on that."</p>
</blockquote>
<p>Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in <a href="http://pastebin.com/f5f5cf9ab">this pastebin</a>.</p>
<p>I am still rather new with regular expressions myself, so I am looking for some assistance.</p>
| 12 | 2008-11-22T20:50:33Z | 311,769 | <p>It's simpler to use split than a regex.</p>
<pre><code>>>> line="$GPRMC,092204.999,4250.5589,S,14718.5084,E,1,12,24.4,89.6,M,,,0000*1F "
>>> line.split(',')
['$GPRMC', '092204.999', '4250.5589', 'S', '14718.5084', 'E', '1', '12', '24.4', '89.6', 'M', '', '', '0000*1F ']
>>>
</code></pre>
| 8 | 2008-11-22T20:54:18Z | [
"python",
"regex",
"parsing",
"gps",
"nmea"
]
|
Parsing GPS receiver output via regex in Python | 311,763 | <p>I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus.</p>
<p>Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice.</p>
<p>At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold:</p>
<p>$GPRMC,092204.999,<strong>4250.5589,S,14718.5084,E</strong>,1,12,24.4,<strong>89.6</strong>,M,,,0000*1F
$GPRMC,093345.679,<strong>4234.7899,N,11344.2567,W</strong>,3,02,24.5,<strong>1000.23</strong>,M,,,0000*1F
$GPRMC,044584.936,<strong>1276.5539,N,88734.1543,E</strong>,2,04,33.5,<strong>600.323</strong>,M,,,*00
$GPRMC,199304.973,<strong>3248.7780,N,11355.7832,W</strong>,1,06,02.2,<strong>25722.5</strong>,M,,,*00
$GPRMC,066487.954,<strong>4572.0089,S,45572.3345,W</strong>,3,09,15.0,<strong>35000.00</strong>,M,,,*1F</p>
<p>Here is some further explanation of the data:</p>
<blockquote>
<p>"I looks like I'll need five things
out of every line. And bear in mind
that any one of these area's may be
empty. Meaning there will be just two
commas right next to each other. Such
as ',,,' There are two fields that may
be full at any time. Some of them only
have two or three options that they
may be but I don't think I should be
counting on that."</p>
</blockquote>
<p>Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in <a href="http://pastebin.com/f5f5cf9ab">this pastebin</a>.</p>
<p>I am still rather new with regular expressions myself, so I am looking for some assistance.</p>
| 12 | 2008-11-22T20:50:33Z | 311,778 | <p>splitting should do the trick. Here's a good way to extract the data, as well:</p>
<pre><code>>>> line = "$GPRMC,199304.973,3248.7780,N,11355.7832,W,1,06,02.2,25722.5,M,,,*00"
>>> line = line.split(",")
>>> neededData = (float(line[2]), line[3], float(line[4]), line[5], float(line[9]))
>>> print neededData
(3248.7779999999998, 'N', 11355.7832, 'W', 25722.5)
</code></pre>
| 14 | 2008-11-22T21:00:01Z | [
"python",
"regex",
"parsing",
"gps",
"nmea"
]
|
Parsing GPS receiver output via regex in Python | 311,763 | <p>I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus.</p>
<p>Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice.</p>
<p>At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold:</p>
<p>$GPRMC,092204.999,<strong>4250.5589,S,14718.5084,E</strong>,1,12,24.4,<strong>89.6</strong>,M,,,0000*1F
$GPRMC,093345.679,<strong>4234.7899,N,11344.2567,W</strong>,3,02,24.5,<strong>1000.23</strong>,M,,,0000*1F
$GPRMC,044584.936,<strong>1276.5539,N,88734.1543,E</strong>,2,04,33.5,<strong>600.323</strong>,M,,,*00
$GPRMC,199304.973,<strong>3248.7780,N,11355.7832,W</strong>,1,06,02.2,<strong>25722.5</strong>,M,,,*00
$GPRMC,066487.954,<strong>4572.0089,S,45572.3345,W</strong>,3,09,15.0,<strong>35000.00</strong>,M,,,*1F</p>
<p>Here is some further explanation of the data:</p>
<blockquote>
<p>"I looks like I'll need five things
out of every line. And bear in mind
that any one of these area's may be
empty. Meaning there will be just two
commas right next to each other. Such
as ',,,' There are two fields that may
be full at any time. Some of them only
have two or three options that they
may be but I don't think I should be
counting on that."</p>
</blockquote>
<p>Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in <a href="http://pastebin.com/f5f5cf9ab">this pastebin</a>.</p>
<p>I am still rather new with regular expressions myself, so I am looking for some assistance.</p>
| 12 | 2008-11-22T20:50:33Z | 311,880 | <p>You should also first check the checksum of the data. It is calculated by XORing the characters between the $ and the * (not including them) and comparing it to the hex value at the end.</p>
<p>Your pastebin looks like it has some corrupt lines in it. Here is a simple check, it assumes that the line starts with $ and has no CR/LF at the end. To build a more robust parser you need to search for the '$' and work through the string until hitting the '*'.</p>
<pre><code>def check_nmea0183(s):
"""
Check a string to see if it is a valid NMEA 0183 sentence
"""
if s[0] != '$':
return False
if s[-3] != '*':
return False
checksum = 0
for c in s[1:-3]:
checksum ^= ord(c)
if int(s[-2:],16) != checksum:
return False
return True
</code></pre>
| 4 | 2008-11-22T23:09:34Z | [
"python",
"regex",
"parsing",
"gps",
"nmea"
]
|
Parsing GPS receiver output via regex in Python | 311,763 | <p>I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus.</p>
<p>Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice.</p>
<p>At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold:</p>
<p>$GPRMC,092204.999,<strong>4250.5589,S,14718.5084,E</strong>,1,12,24.4,<strong>89.6</strong>,M,,,0000*1F
$GPRMC,093345.679,<strong>4234.7899,N,11344.2567,W</strong>,3,02,24.5,<strong>1000.23</strong>,M,,,0000*1F
$GPRMC,044584.936,<strong>1276.5539,N,88734.1543,E</strong>,2,04,33.5,<strong>600.323</strong>,M,,,*00
$GPRMC,199304.973,<strong>3248.7780,N,11355.7832,W</strong>,1,06,02.2,<strong>25722.5</strong>,M,,,*00
$GPRMC,066487.954,<strong>4572.0089,S,45572.3345,W</strong>,3,09,15.0,<strong>35000.00</strong>,M,,,*1F</p>
<p>Here is some further explanation of the data:</p>
<blockquote>
<p>"I looks like I'll need five things
out of every line. And bear in mind
that any one of these area's may be
empty. Meaning there will be just two
commas right next to each other. Such
as ',,,' There are two fields that may
be full at any time. Some of them only
have two or three options that they
may be but I don't think I should be
counting on that."</p>
</blockquote>
<p>Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in <a href="http://pastebin.com/f5f5cf9ab">this pastebin</a>.</p>
<p>I am still rather new with regular expressions myself, so I am looking for some assistance.</p>
| 12 | 2008-11-22T20:50:33Z | 313,431 | <p>Those are comma separated values, so using a csv library is the easiest solution.</p>
<p>I threw that sample data you have into /var/tmp/sampledata, then I did this:</p>
<pre><code>>>> import csv
>>> for line in csv.reader(open('/var/tmp/sampledata')):
... print line
['$GPRMC', '092204.999', '**4250.5589', 'S', '14718.5084', 'E**', '1', '12', '24.4', '**89.6**', 'M', '', '', '0000\\*1F']
['$GPRMC', '093345.679', '**4234.7899', 'N', '11344.2567', 'W**', '3', '02', '24.5', '**1000.23**', 'M', '', '', '0000\\*1F']
['$GPRMC', '044584.936', '**1276.5539', 'N', '88734.1543', 'E**', '2', '04', '33.5', '**600.323**', 'M', '', '', '\\*00']
['$GPRMC', '199304.973', '**3248.7780', 'N', '11355.7832', 'W**', '1', '06', '02.2', '**25722.5**', 'M', '', '', '\\*00']
['$GPRMC', '066487.954', '**4572.0089', 'S', '45572.3345', 'W**', '3', '09', '15.0', '**35000.00**', 'M', '', '', '\\*1F']
</code></pre>
<p>You can then process the data however you wish. It looks a little odd with the '**' at the start and end of some of the values, you might want to strip that stuff off, you can do:</p>
<pre><code>>> eastwest = 'E**'
>> eastwest = eastwest.strip('*')
>> print eastwest
E
</code></pre>
<p>You will have to cast some values as floats. So for example, the 3rd value on the first line of sample data is:</p>
<pre><code>>> data = '**4250.5589'
>> print float(data.strip('*'))
4250.5589
</code></pre>
| 5 | 2008-11-24T04:49:39Z | [
"python",
"regex",
"parsing",
"gps",
"nmea"
]
|
Parsing GPS receiver output via regex in Python | 311,763 | <p>I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus.</p>
<p>Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice.</p>
<p>At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold:</p>
<p>$GPRMC,092204.999,<strong>4250.5589,S,14718.5084,E</strong>,1,12,24.4,<strong>89.6</strong>,M,,,0000*1F
$GPRMC,093345.679,<strong>4234.7899,N,11344.2567,W</strong>,3,02,24.5,<strong>1000.23</strong>,M,,,0000*1F
$GPRMC,044584.936,<strong>1276.5539,N,88734.1543,E</strong>,2,04,33.5,<strong>600.323</strong>,M,,,*00
$GPRMC,199304.973,<strong>3248.7780,N,11355.7832,W</strong>,1,06,02.2,<strong>25722.5</strong>,M,,,*00
$GPRMC,066487.954,<strong>4572.0089,S,45572.3345,W</strong>,3,09,15.0,<strong>35000.00</strong>,M,,,*1F</p>
<p>Here is some further explanation of the data:</p>
<blockquote>
<p>"I looks like I'll need five things
out of every line. And bear in mind
that any one of these area's may be
empty. Meaning there will be just two
commas right next to each other. Such
as ',,,' There are two fields that may
be full at any time. Some of them only
have two or three options that they
may be but I don't think I should be
counting on that."</p>
</blockquote>
<p>Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in <a href="http://pastebin.com/f5f5cf9ab">this pastebin</a>.</p>
<p>I am still rather new with regular expressions myself, so I am looking for some assistance.</p>
| 12 | 2008-11-22T20:50:33Z | 5,203,090 | <p>If you need to do some more extensive analysis of your GPS data streams, here is a pyparsing solution that breaks up your data into named data fields. I extracted your pastebin'ned data to a file gpsstream.txt, and parsed it with the following:</p>
<pre><code>"""
Parse NMEA 0183 codes for GPS data
http://en.wikipedia.org/wiki/NMEA_0183
(data formats from http://www.gpsinformation.org/dale/nmea.htm)
"""
from pyparsing import *
lead = "$"
code = Word(alphas.upper(),exact=5)
end = "*"
COMMA = Suppress(',')
cksum = Word(hexnums,exact=2).setParseAction(lambda t:int(t[0],16))
# define basic data value forms, and attach conversion actions
word = Word(alphanums)
N,S,E,W = map(Keyword,"NSEW")
integer = Regex(r"-?\d+").setParseAction(lambda t:int(t[0]))
real = Regex(r"-?\d+\.\d*").setParseAction(lambda t:float(t[0]))
timestamp = Regex(r"\d{2}\d{2}\d{2}\.\d+")
timestamp.setParseAction(lambda t: t[0][:2]+':'+t[0][2:4]+':'+t[0][4:])
def lonlatConversion(t):
t["deg"] = int(t.deg)
t["min"] = float(t.min)
t["value"] = ((t.deg + t.min/60.0)
* {'N':1,'S':-1,'':1}[t.ns]
* {'E':1,'W':-1,'':1}[t.ew])
lat = Regex(r"(?P<deg>\d{2})(?P<min>\d{2}\.\d+),(?P<ns>[NS])").setParseAction(lonlatConversion)
lon = Regex(r"(?P<deg>\d{3})(?P<min>\d{2}\.\d+),(?P<ew>[EW])").setParseAction(lonlatConversion)
# define expression for a complete data record
value = timestamp | Group(lon) | Group(lat) | real | integer | N | S | E | W | word
item = lead + code("code") + COMMA + delimitedList(Optional(value,None))("datafields") + end + cksum("cksum")
def parseGGA(tokens):
keys = "time lat lon qual numsats horiz_dilut alt _ geoid_ht _ last_update_secs stnid".split()
for k,v in zip(keys, tokens.datafields):
if k != '_':
tokens[k] = v
#~ print tokens.dump()
def parseGSA(tokens):
keys = "auto_manual _3dfix prn prn prn prn prn prn prn prn prn prn prn prn pdop hdop vdop".split()
tokens["prn"] = []
for k,v in zip(keys, tokens.datafields):
if k != 'prn':
tokens[k] = v
else:
if v is not None:
tokens[k].append(v)
#~ print tokens.dump()
def parseRMC(tokens):
keys = "time active_void lat lon speed track_angle date mag_var _ signal_integrity".split()
for k,v in zip(keys, tokens.datafields):
if k != '_':
if k == 'date' and v is not None:
v = "%06d" % v
tokens[k] = '20%s/%s/%s' % (v[4:],v[2:4],v[:2])
else:
tokens[k] = v
#~ print tokens.dump()
# process sample data
data = open("gpsstream.txt").read().expandtabs()
count = 0
for i,s,e in item.scanString(data):
# use checksum to validate input
linebody = data[s+1:e-3]
checksum = reduce(lambda a,b:a^b, map(ord, linebody))
if i.cksum != checksum:
continue
count += 1
# parse out specific data fields, depending on code field
fn = {'GPGGA' : parseGGA,
'GPGSA' : parseGSA,
'GPRMC' : parseRMC,}[i.code]
fn(i)
# print out time/position/speed values
if i.code == 'GPRMC':
print "%s %8.3f %8.3f %4d" % (i.time, i.lat.value, i.lon.value, i.speed or 0)
print count
</code></pre>
<p>The $GPRMC records in your pastebin don't seem to quite match with the ones you included in your post, but you should be able to adjust this example as necessary.</p>
| 2 | 2011-03-05T10:04:34Z | [
"python",
"regex",
"parsing",
"gps",
"nmea"
]
|
Parsing GPS receiver output via regex in Python | 311,763 | <p>I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus.</p>
<p>Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice.</p>
<p>At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold:</p>
<p>$GPRMC,092204.999,<strong>4250.5589,S,14718.5084,E</strong>,1,12,24.4,<strong>89.6</strong>,M,,,0000*1F
$GPRMC,093345.679,<strong>4234.7899,N,11344.2567,W</strong>,3,02,24.5,<strong>1000.23</strong>,M,,,0000*1F
$GPRMC,044584.936,<strong>1276.5539,N,88734.1543,E</strong>,2,04,33.5,<strong>600.323</strong>,M,,,*00
$GPRMC,199304.973,<strong>3248.7780,N,11355.7832,W</strong>,1,06,02.2,<strong>25722.5</strong>,M,,,*00
$GPRMC,066487.954,<strong>4572.0089,S,45572.3345,W</strong>,3,09,15.0,<strong>35000.00</strong>,M,,,*1F</p>
<p>Here is some further explanation of the data:</p>
<blockquote>
<p>"I looks like I'll need five things
out of every line. And bear in mind
that any one of these area's may be
empty. Meaning there will be just two
commas right next to each other. Such
as ',,,' There are two fields that may
be full at any time. Some of them only
have two or three options that they
may be but I don't think I should be
counting on that."</p>
</blockquote>
<p>Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in <a href="http://pastebin.com/f5f5cf9ab">this pastebin</a>.</p>
<p>I am still rather new with regular expressions myself, so I am looking for some assistance.</p>
| 12 | 2008-11-22T20:50:33Z | 7,214,844 | <p>I suggest a small fix in your code because if used to parse data from the previous century the date looks like sometime in the future (for instance 2094 instead of 1994)</p>
<p>My fix is not fully accurate, but I take the stand that prior to the 70's no GPS data existed.</p>
<p>In the def parse function for RMC sentences just replace the format line by:</p>
<pre><code>p = int(v[4:])
print "p = ", p
if p > 70:
tokens[k] = '19%s/%s/%s' % (v[4:],v[2:4],v[:2])
else:
tokens[k] = '20%s/%s/%s' % (v[4:],v[2:4],v[:2])
</code></pre>
<p>This will look at the two yy digits of the year and assume that past year 70 we are dealing with sentences from the previous century.
It could be better done by comparing to today's date and assuming that every time you deal with some data in the future, they are in fact from the past century</p>
<p>Thanks for all the pieces of code your provided above... I had some fun with this.</p>
| 1 | 2011-08-27T13:28:45Z | [
"python",
"regex",
"parsing",
"gps",
"nmea"
]
|
Parsing GPS receiver output via regex in Python | 311,763 | <p>I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus.</p>
<p>Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice.</p>
<p>At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold:</p>
<p>$GPRMC,092204.999,<strong>4250.5589,S,14718.5084,E</strong>,1,12,24.4,<strong>89.6</strong>,M,,,0000*1F
$GPRMC,093345.679,<strong>4234.7899,N,11344.2567,W</strong>,3,02,24.5,<strong>1000.23</strong>,M,,,0000*1F
$GPRMC,044584.936,<strong>1276.5539,N,88734.1543,E</strong>,2,04,33.5,<strong>600.323</strong>,M,,,*00
$GPRMC,199304.973,<strong>3248.7780,N,11355.7832,W</strong>,1,06,02.2,<strong>25722.5</strong>,M,,,*00
$GPRMC,066487.954,<strong>4572.0089,S,45572.3345,W</strong>,3,09,15.0,<strong>35000.00</strong>,M,,,*1F</p>
<p>Here is some further explanation of the data:</p>
<blockquote>
<p>"I looks like I'll need five things
out of every line. And bear in mind
that any one of these area's may be
empty. Meaning there will be just two
commas right next to each other. Such
as ',,,' There are two fields that may
be full at any time. Some of them only
have two or three options that they
may be but I don't think I should be
counting on that."</p>
</blockquote>
<p>Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in <a href="http://pastebin.com/f5f5cf9ab">this pastebin</a>.</p>
<p>I am still rather new with regular expressions myself, so I am looking for some assistance.</p>
| 12 | 2008-11-22T20:50:33Z | 23,948,187 | <p>You could use a library like <a href="https://github.com/Knio/pynmea2" rel="nofollow">pynmea2</a> for parsing the NMEA log.</p>
<pre><code>>>> import pynmea2
>>> msg = pynmea2.parse('$GPGGA,142927.829,2831.4705,N,08041.0067,W,1,07,1.0,7.9,M,-31.2,M,0.0,0000*4F')
>>> msg.timestamp, msg.latitude, msg.longitude, msg.altitude
(datetime.time(14, 29, 27), 28.524508333333333, -80.683445, 7.9)
</code></pre>
<p>Disclaimer: I am the author of pynmea2</p>
| 2 | 2014-05-30T06:11:12Z | [
"python",
"regex",
"parsing",
"gps",
"nmea"
]
|
Python - Create a list with initial capacity | 311,775 | <p>Code like this often happens:</p>
<pre><code>l = []
while foo:
#baz
l.append(bar)
#qux
</code></pre>
<p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p>
<p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p>
<p>I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers?</p>
| 110 | 2008-11-22T20:56:41Z | 311,783 | <p>Python lists have no built-in pre-allocation. If you really need to make a list, and need to avoid the overhead of appending (and you should verify that you do), you can do this:</p>
<pre><code>l = [None] * 1000 # Make a list of 1000 None's
for i in xrange(1000):
# baz
l[i] = bar
# qux
</code></pre>
<p>Perhaps you could avoid the list by using a generator instead:</p>
<pre><code>def my_things():
while foo:
#baz
yield bar
#qux
for thing in my_things():
# do something with thing
</code></pre>
<p>This way, the list isn't every stored all in memory at all, merely generated as needed.</p>
| 43 | 2008-11-22T21:07:18Z | [
"python",
"list",
"dictionary",
"initialization"
]
|
Python - Create a list with initial capacity | 311,775 | <p>Code like this often happens:</p>
<pre><code>l = []
while foo:
#baz
l.append(bar)
#qux
</code></pre>
<p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p>
<p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p>
<p>I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers?</p>
| 110 | 2008-11-22T20:56:41Z | 311,785 | <p>From what I understand, python lists are already quite similar to ArrayLists. But if you want to tweak those parameters I found this post on the net that may be interesting (basically, just create your own <code>ScalableList</code> extension):</p>
<p><a href="http://mail.python.org/pipermail/python-list/2000-May/035082.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2000-May/035082.html</a></p>
| 0 | 2008-11-22T21:07:56Z | [
"python",
"list",
"dictionary",
"initialization"
]
|
Python - Create a list with initial capacity | 311,775 | <p>Code like this often happens:</p>
<pre><code>l = []
while foo:
#baz
l.append(bar)
#qux
</code></pre>
<p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p>
<p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p>
<p>I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers?</p>
| 110 | 2008-11-22T20:56:41Z | 311,833 | <pre><code>def doAppend( size=10000 ):
result = []
for i in range(size):
message= "some unique object %d" % ( i, )
result.append(message)
return result
def doAllocate( size=10000 ):
result=size*[None]
for i in range(size):
message= "some unique object %d" % ( i, )
result[i]= message
return result
</code></pre>
<p><strong>Results</strong>. (evaluate each function 144 times and average the duration)</p>
<pre><code>simple append 0.0102
pre-allocate 0.0098
</code></pre>
<p><strong>Conclusion</strong>. It barely matters. </p>
<p>Premature optimization is the root of all evil.</p>
| 89 | 2008-11-22T22:02:34Z | [
"python",
"list",
"dictionary",
"initialization"
]
|
Python - Create a list with initial capacity | 311,775 | <p>Code like this often happens:</p>
<pre><code>l = []
while foo:
#baz
l.append(bar)
#qux
</code></pre>
<p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p>
<p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p>
<p>I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers?</p>
| 110 | 2008-11-22T20:56:41Z | 1,602,958 | <p>i ran @s.lott's code and produced the same 10% perf increase by pre-allocating. tried @jeremy's idea using a generator and was able to see the perf of the gen better than that of the doAllocate. For my proj the 10% improvement matters, so thanks to everyone as this helps a bunch.</p>
<pre><code>def doAppend( size=10000 ):
result = []
for i in range(size):
message= "some unique object %d" % ( i, )
result.append(message)
return result
def doAllocate( size=10000 ):
result=size*[None]
for i in range(size):
message= "some unique object %d" % ( i, )
result[i]= message
return result
def doGen( size=10000 ):
return list("some unique object %d" % ( i, ) for i in xrange(size))
size=1000
@print_timing
def testAppend():
for i in xrange(size):
doAppend()
@print_timing
def testAlloc():
for i in xrange(size):
doAllocate()
@print_timing
def testGen():
for i in xrange(size):
doGen()
testAppend()
testAlloc()
testGen()
testAppend took 14440.000ms
testAlloc took 13580.000ms
testGen took 13430.000ms
</code></pre>
| 4 | 2009-10-21T19:09:38Z | [
"python",
"list",
"dictionary",
"initialization"
]
|
Python - Create a list with initial capacity | 311,775 | <p>Code like this often happens:</p>
<pre><code>l = []
while foo:
#baz
l.append(bar)
#qux
</code></pre>
<p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p>
<p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p>
<p>I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers?</p>
| 110 | 2008-11-22T20:56:41Z | 5,533,598 | <p>Short version: use</p>
<pre><code>pre_allocated_list = [None] * size
</code></pre>
<p>to pre-allocate a list (that is, to be able to address 'size' elements of the list instead of gradually forming the list by appending). This operation is VERY fast, even on big lists. Allocating new objects that will be later assigned to list elements will take MUCH longer and will be THE bottleneck in your program, performance-wise.</p>
<p>Long version:</p>
<p>I think that initialization time should be taken into account.
Since in python everything is a reference, it doesn't matter whether you set each element into None or some string - either way it's only a reference. Though it will take longer if you want to create new object for each element to reference.</p>
<p>For Python 3.2:</p>
<pre><code>import time
import copy
def print_timing (func):
def wrapper (*arg):
t1 = time.time ()
res = func (*arg)
t2 = time.time ()
print ("{} took {} ms".format (func.__name__, (t2 - t1) * 1000.0))
return res
return wrapper
@print_timing
def prealloc_array (size, init = None, cp = True, cpmethod=copy.deepcopy, cpargs=(), use_num = False):
result = [None] * size
if init is not None:
if cp:
for i in range (size):
result[i] = init
else:
if use_num:
for i in range (size):
result[i] = cpmethod (i)
else:
for i in range (size):
result[i] = cpmethod (cpargs)
return result
@print_timing
def prealloc_array_by_appending (size):
result = []
for i in range (size):
result.append (None)
return result
@print_timing
def prealloc_array_by_extending (size):
result = []
none_list = [None]
for i in range (size):
result.extend (none_list)
return result
def main ():
n = 1000000
x = prealloc_array_by_appending(n)
y = prealloc_array_by_extending(n)
a = prealloc_array(n, None)
b = prealloc_array(n, "content", True)
c = prealloc_array(n, "content", False, "some object {}".format, ("blah"), False)
d = prealloc_array(n, "content", False, "some object {}".format, None, True)
e = prealloc_array(n, "content", False, copy.deepcopy, "a", False)
f = prealloc_array(n, "content", False, copy.deepcopy, (), False)
g = prealloc_array(n, "content", False, copy.deepcopy, [], False)
print ("x[5] = {}".format (x[5]))
print ("y[5] = {}".format (y[5]))
print ("a[5] = {}".format (a[5]))
print ("b[5] = {}".format (b[5]))
print ("c[5] = {}".format (c[5]))
print ("d[5] = {}".format (d[5]))
print ("e[5] = {}".format (e[5]))
print ("f[5] = {}".format (f[5]))
print ("g[5] = {}".format (g[5]))
if __name__ == '__main__':
main()
</code></pre>
<p>Evaluation:</p>
<pre><code>prealloc_array_by_appending took 118.00003051757812 ms
prealloc_array_by_extending took 102.99992561340332 ms
prealloc_array took 3.000020980834961 ms
prealloc_array took 49.00002479553223 ms
prealloc_array took 316.9999122619629 ms
prealloc_array took 473.00004959106445 ms
prealloc_array took 1677.9999732971191 ms
prealloc_array took 2729.999780654907 ms
prealloc_array took 3001.999855041504 ms
x[5] = None
y[5] = None
a[5] = None
b[5] = content
c[5] = some object blah
d[5] = some object 5
e[5] = a
f[5] = []
g[5] = ()
</code></pre>
<p>As you can see, just making a big list of references to the same None object takes very little time. </p>
<p>Prepending or extending takes longer (i didn't average anything, but after running this a few times i can tell you that extending and appending take roughly the same time).</p>
<p>Allocating new object for each element - that is what takes the most time. And S.Lott's answer does that - formats a new string every time. Which is not strictly required - if you want to pre-allocate some space, just make a list of None, then assign data to list elements at will. Either way it takes more time to generate data than to append/extend a list, whether you generate it while creating the list, or after that. But if you want a sparsely-populated list, then starting with a list of None is definitely faster.</p>
| 22 | 2011-04-04T00:48:00Z | [
"python",
"list",
"dictionary",
"initialization"
]
|
Python - Create a list with initial capacity | 311,775 | <p>Code like this often happens:</p>
<pre><code>l = []
while foo:
#baz
l.append(bar)
#qux
</code></pre>
<p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p>
<p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p>
<p>I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers?</p>
| 110 | 2008-11-22T20:56:41Z | 24,173,567 | <p>The Pythonic way for this is:</p>
<pre><code>x = [None] * numElements
</code></pre>
<p>or whatever default value you wish to prepop with, e.g.</p>
<pre><code>bottles = [Beer()] * 99
sea = [Fish()] * many
vegetarianPizzas = [None] * peopleOrderingPizzaNotQuiche
</code></pre>
<p>Python's default approach can be pretty efficient, although that efficiency decays as you increase the number of elements.</p>
<p>Compare</p>
<pre><code>import time
class Timer(object):
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
end = time.time()
secs = end - self.start
msecs = secs * 1000 # millisecs
print('%fms' % msecs)
Elements = 100000
Iterations = 144
print('Elements: %d, Iterations: %d' % (Elements, Iterations))
def doAppend():
result = []
i = 0
while i < Elements:
result.append(i)
i += 1
def doAllocate():
result = [None] * Elements
i = 0
while i < Elements:
result[i] = i
i += 1
def doGenerator():
return list(i for i in range(Elements))
def test(name, fn):
print("%s: " % name, end="")
with Timer() as t:
x = 0
while x < Iterations:
fn()
x += 1
test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)
</code></pre>
<p>with</p>
<pre><code>#include <vector>
typedef std::vector<unsigned int> Vec;
static const unsigned int Elements = 100000;
static const unsigned int Iterations = 144;
void doAppend()
{
Vec v;
for (unsigned int i = 0; i < Elements; ++i) {
v.push_back(i);
}
}
void doReserve()
{
Vec v;
v.reserve(Elements);
for (unsigned int i = 0; i < Elements; ++i) {
v.push_back(i);
}
}
void doAllocate()
{
Vec v;
v.resize(Elements);
for (unsigned int i = 0; i < Elements; ++i) {
v[i] = i;
}
}
#include <iostream>
#include <chrono>
using namespace std;
void test(const char* name, void(*fn)(void))
{
cout << name << ": ";
auto start = chrono::high_resolution_clock::now();
for (unsigned int i = 0; i < Iterations; ++i) {
fn();
}
auto end = chrono::high_resolution_clock::now();
auto elapsed = end - start;
cout << chrono::duration<double, milli>(elapsed).count() << "ms\n";
}
int main()
{
cout << "Elements: " << Elements << ", Iterations: " << Iterations << '\n';
test("doAppend", doAppend);
test("doReserve", doReserve);
test("doAllocate", doAllocate);
}
</code></pre>
<p>On my Windows 7 i7, 64-bit Python gives</p>
<pre><code>Elements: 100000, Iterations: 144
doAppend: 3587.204933ms
doAllocate: 2701.154947ms
doGenerator: 1721.098185ms
</code></pre>
<p>While C++ gives (built with MSVC, 64-bit, Optimizations enabled)</p>
<pre><code>Elements: 100000, Iterations: 144
doAppend: 74.0042ms
doReserve: 27.0015ms
doAllocate: 5.0003ms
</code></pre>
<p>C++ debug build produces:</p>
<pre><code>Elements: 100000, Iterations: 144
doAppend: 2166.12ms
doReserve: 2082.12ms
doAllocate: 273.016ms
</code></pre>
<p>The point here is that with Python you can achieve a 7-8% performance improvement, and if you think you're writing a high-performance app (or if you're writing something that is used in a web service or something) then that isn't to be sniffed at, but you may need to rethink your choice of language.</p>
<p>Also, the Python code here isn't really Python code. Switching to truly Pythonesque code here gives better performance:</p>
<pre><code>import time
class Timer(object):
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
end = time.time()
secs = end - self.start
msecs = secs * 1000 # millisecs
print('%fms' % msecs)
Elements = 100000
Iterations = 144
print('Elements: %d, Iterations: %d' % (Elements, Iterations))
def doAppend():
for x in range(Iterations):
result = []
for i in range(Elements):
result.append(i)
def doAllocate():
for x in range(Iterations):
result = [None] * Elements
for i in range(Elements):
result[i] = i
def doGenerator():
for x in range(Iterations):
result = list(i for i in range(Elements))
def test(name, fn):
print("%s: " % name, end="")
with Timer() as t:
fn()
test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)
</code></pre>
<p>Which gives</p>
<pre><code>Elements: 100000, Iterations: 144
doAppend: 2153.122902ms
doAllocate: 1346.076965ms
doGenerator: 1614.092112ms
</code></pre>
<p>(in 32-bit doGenerator does better than doAllocate).</p>
<p>Here the gap between doAppend and doAllocate is significantly larger.</p>
<p>Obviously, the differences here really only apply if you are doing this more than a handful of times or if you are doing this on a heavily loaded system where those numbers are going to get scaled out by orders of magnitude, or if you are dealing with considerably larger lists.</p>
<p>The point here: Do it the pythonic way for the best performance.</p>
<p>But if you are worrying about general, high-level performance, Python is the wrong language. The most fundamental problem being that Python function calls has traditionally been upto 300x slower than other languages due to Python features like decorators etc (<a href="https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Data_Aggregation#Data_Aggregation" rel="nofollow">https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Data_Aggregation#Data_Aggregation</a>).</p>
| 10 | 2014-06-11T22:21:01Z | [
"python",
"list",
"dictionary",
"initialization"
]
|
Python - Create a list with initial capacity | 311,775 | <p>Code like this often happens:</p>
<pre><code>l = []
while foo:
#baz
l.append(bar)
#qux
</code></pre>
<p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p>
<p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p>
<p>I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers?</p>
| 110 | 2008-11-22T20:56:41Z | 25,027,798 | <p>Concerns about pre-allocation in Python arise if you're working with numpy, which has more C-like arrays. In this instance, pre-allocation concerns are about the shape of the data and the default value.</p>
<p>Consider numpy if you're doing numerical computation on massive lists and want performance.</p>
| 2 | 2014-07-30T02:22:33Z | [
"python",
"list",
"dictionary",
"initialization"
]
|
How do I not raise a Python exception when converting an integer-as-string to an int | 311,963 | <p>I have some HTML I am trying to parse. There are cases where the html attributes alone are not going to help me identify the row type (header versus data). Fortunately, if my row is a data row then it should have some values that can be converted to integers. I have figured out how to convert the unicode to an integer for those cases that it is possible to make the conversion. I am struggling to write the logic to move past the cells that the conversion will not work because the cell has content that must be treated as text.</p>
<p>for example if rowColumn[1][3] can be converted to an integer I can do so by </p>
<pre><code>int(rowColumn[1][3].replace(',','').strip('$'))
</code></pre>
<p>but I get an error if rowColumn[1][3] has text content.</p>
| 1 | 2008-11-23T01:01:56Z | 311,968 | <p>Have you looked at the try statement?</p>
<pre><code>try:
x = int(rowColumn[1][3].replace(',','').strip('$'))
except ValueError, e:
x = None # rowColumn[1][3] was not an integer
</code></pre>
| 4 | 2008-11-23T01:05:32Z | [
"python",
"text",
"integer"
]
|
Effective Keyboard Input Handling | 312,263 | <p>What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this:</p>
<pre><code>for event in pygame.event.get():
if event.type == KEYDOWN:
if False: pass #make everything an elif
elif rotating: pass
elif event.key == K_q:
elif event.key == K_e:
elif event.key == K_LEFT:
curpiece.shift(-1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
elif event.key == K_RIGHT:
curpiece.shift(1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
</code></pre>
<p>(shortened). I don't like this, as this has to go in my main loop, and it messes with all parts of the program. This also makes it impossible to have a user config screen where they can change which key maps to which action. Is there a good pattern to do this using some form of function callbacks?</p>
| 9 | 2008-11-23T07:26:06Z | 312,270 | <p>You could create a dictionary where the keys are the input and the value is a function that handles the keypress:</p>
<pre><code>def handle_quit():
quit()
def handle_left():
curpiece.shift(-1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
def handle_right():
curpiece.shift(1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
def handle_pause():
if not paused:
paused = True
branch = {
K_q: handle_quit
K_e: handle_pause
K_LEFT: handle_left
K_RIGHT: handle_right
}
for event in pygame.event.get():
if event.type == KEYDOWN:
branch[event.key]()
</code></pre>
<p>Then changing the keys is a matter of modifying keys of the dictionary.</p>
| 17 | 2008-11-23T07:32:57Z | [
"python",
"user-interface",
"keyboard",
"user-input",
"interactive"
]
|
Effective Keyboard Input Handling | 312,263 | <p>What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this:</p>
<pre><code>for event in pygame.event.get():
if event.type == KEYDOWN:
if False: pass #make everything an elif
elif rotating: pass
elif event.key == K_q:
elif event.key == K_e:
elif event.key == K_LEFT:
curpiece.shift(-1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
elif event.key == K_RIGHT:
curpiece.shift(1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
</code></pre>
<p>(shortened). I don't like this, as this has to go in my main loop, and it messes with all parts of the program. This also makes it impossible to have a user config screen where they can change which key maps to which action. Is there a good pattern to do this using some form of function callbacks?</p>
| 9 | 2008-11-23T07:26:06Z | 312,882 | <p>in addition to <a href="http://stackoverflow.com/questions/312263/effective-keyboard-input-handling#312270">superjoe30's answer</a>, you can use two levels of mapping (two dictionaries)</p>
<ul>
<li>key => command string</li>
<li>command string => function</li>
</ul>
<p>I think this would make it easier to allow user-defined mappings. i.e. so users can map their keys to "commands" rather than "the name of a function"</p>
| 3 | 2008-11-23T20:03:50Z | [
"python",
"user-interface",
"keyboard",
"user-input",
"interactive"
]
|
Effective Keyboard Input Handling | 312,263 | <p>What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this:</p>
<pre><code>for event in pygame.event.get():
if event.type == KEYDOWN:
if False: pass #make everything an elif
elif rotating: pass
elif event.key == K_q:
elif event.key == K_e:
elif event.key == K_LEFT:
curpiece.shift(-1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
elif event.key == K_RIGHT:
curpiece.shift(1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
</code></pre>
<p>(shortened). I don't like this, as this has to go in my main loop, and it messes with all parts of the program. This also makes it impossible to have a user config screen where they can change which key maps to which action. Is there a good pattern to do this using some form of function callbacks?</p>
| 9 | 2008-11-23T07:26:06Z | 314,000 | <p>What I do nowadays is have some sort of input gathering class/function/thread which will check a list of predefined key->event bindings.</p>
<p>Something like this:</p>
<pre><code>class InputHandler:
def __init__ (self, eventDispatcher):
self.keys = {}
self.eventDispatcher = eventDispatcher
def add_key_binding (self, key, event):
self.keys.update((key, event,))
def gather_input (self):
for event in pygame.event.get():
if event.type == KEYDOWN:
event = self.keys.get(event.key, None)
if not event is None:
self.eventDispatcher.dispatch(event)
....
inputHandler = InputHandler(EventDispatcher)
inputHandler.add_key_binding(K_q, "quit_event")
...
inputHandler.gather_input()
....
</code></pre>
<p>It's basically what superjoe30 is doing, except that instead of calling callbacks directly, I add another level of separation by using an event dispatching system, so that any code that cares about the keys being pressed simply listen for that event.</p>
<p>Also, keys can be easily bound to different events, which could be read from a config file or something and any key which is not bound to an event is simply ignored.</p>
| 2 | 2008-11-24T12:05:58Z | [
"python",
"user-interface",
"keyboard",
"user-input",
"interactive"
]
|
Fetching attachments from gmail via either python or php | 312,284 | <p>I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail">How can I download all emails with attachments from Gmail?</a></li>
</ul>
| 7 | 2008-11-23T08:03:16Z | 312,317 | <p>You will have to enable IMAP access to your GMail account (Settings â Forwarding and POP/IMAP), and then use <code>imaplib.IMAP4_SSL</code> to access it. </p>
<p>Use the raw text of every message as an argument to <code>email.message_from_string</code> in order to process any attachments.</p>
| 10 | 2008-11-23T09:08:39Z | [
"php",
"python",
"gmail",
"attachment"
]
|
Fetching attachments from gmail via either python or php | 312,284 | <p>I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail">How can I download all emails with attachments from Gmail?</a></li>
</ul>
| 7 | 2008-11-23T08:03:16Z | 3,242,719 | <p>The php docs for imap_open explain connecting to gmail in the comments (e.g. 31-Oct-2007 07:50):</p>
<p><code>$mbox = imap_open("{imap.gmail.com:993/imap/ssl}INBOX", "username@gmail.com", "password") or die("can't connect: " . imap_last_error());</code></p>
<p>Where, obviously, you have to fill in the actual username and password as appropriate, and then to identify the attachments in the parts of the email you follow the instructions from: <a href="http://www.electrictoolbox.com/extract-attachments-email-php-imap/" rel="nofollow">http://www.electrictoolbox.com/extract-attachments-email-php-imap/</a></p>
<p>Which, summarizing, says that you use:</p>
<p><code>// in a for($i=1;$i<$nummsgs;$i++) loop over all the messages in the inbox
$structure = imap_fetchstructure($mbox, $i);</code></p>
<p>to identify the attachments in the structure. However, that is a rather elaborate process of deconstructing MIME messages (which have a lot of optional variability that must be accounted for), so the fundamentals/outline of a function for that is in that electrictoolbox page.</p>
| 0 | 2010-07-14T01:17:43Z | [
"php",
"python",
"gmail",
"attachment"
]
|
Fetching attachments from gmail via either python or php | 312,284 | <p>I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail">How can I download all emails with attachments from Gmail?</a></li>
</ul>
| 7 | 2008-11-23T08:03:16Z | 4,573,629 | <p>I found some code that works! this will download any attachments to a selected folder</p>
<pre><code><?php
$gmail_username = 'username@gmail.com';
$gmail_password = 'mypassword';
$imap = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $gmail_username, $gmail_password) or die("can't connect: " . imap_last_error());
$savefilepath = 'path/to/images_folder/'; //absolute path to images directory
$imagefilepath = 'images/'; //relative path to images directory
$headers = imap_headers($imap);
foreach ($headers as $mail) {
$flags = substr($mail, 0, 4);
//Check for unread msgs, get their UID, and queue them up
if (strpos($flags, "U")) {
preg_match('/[0-9]+/',$mail,$match);
$new_msg[] = implode('',$match);
}
}
if ($new_msg) {
foreach ($new_msg as $result) {
$structure = imap_fetchstructure($imap,$result);
$parts = $structure->parts;
foreach ($parts as $part) {
if ($part->parameters[0]->attribute == "NAME") {
//Generate a filename with format DATE_RANDOM#_ATTACHMENTNAME.EXT
$savefilename = date("m-d-Y") . '_' . mt_rand(rand(), 6) . '_' . $part->parameters[0]->value;
save_attachment(imap_fetchbody($imap,$result,2),$savefilename,$savefilepath,$savethumbpath);
imap_fetchbody($imap,$result,2); //This marks message as read
}
}
}
}
imap_close($imap);
function save_attachment( $content , $filename , $localfilepath, $thumbfilepath ) {
if (imap_base64($content) != FALSE) {
$file = fopen($localfilepath.$filename, 'w');
fwrite($file, imap_base64($content));
fclose($file);
}
}
?>
</code></pre>
| 2 | 2011-01-01T09:08:48Z | [
"php",
"python",
"gmail",
"attachment"
]
|
Fetching attachments from gmail via either python or php | 312,284 | <p>I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail">How can I download all emails with attachments from Gmail?</a></li>
</ul>
| 7 | 2008-11-23T08:03:16Z | 12,956,451 | <p>I took the code above and fixed it and tested it. It works with PHP5.</p>
<pre><code><?php
$gmail_username = 'email@gmail.com';
$gmail_password = 'password';
$imap = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $gmail_username, $gmail_password) or die("can't connect: " . imap_last_error());
$savefilepath = '//Server/share/Local/Pathname/'; //absolute path to images directory
$imagefilepath = '/Local/Pathname/'; //relative path to images directory
$savethumbpath = '/Local/Pathname/'; //relative path to images directory
$headers = imap_headers($imap);
foreach ($headers as $mail) {
$flags = substr($mail, 0, 4);
//Check for unread msgs, get their UID, and queue them up
if (strpos($flags, "U")) {
preg_match('/[0-9]+/',$mail,$match);
$new_msg[] = implode('',$match);
}
}
if ($new_msg) {
foreach ($new_msg as $result) {
$structure = imap_fetchstructure($imap,$result);
$parts = $structure->parts;
foreach ($parts as $part) {
if ($part->parameters[0]->attribute == "NAME") {
//Generate a filename with format DATE_RANDOM#_ATTACHMENTNAME.EXT
$savefilename = date("m-d-Y") . '_' . rand() . '_' . $part->parameters[0]->value;
save_attachment(imap_fetchbody($imap,$result,2),$savefilename,$savefilepath,$savethumbpath);
imap_fetchbody($imap,$result,2); //This marks message as read
}
}
}
}
/* grab emails */
$emails = imap_search($imap,'ALL');
/* if emails are returned, cycle through each... */
if($emails) {
/* put the newest emails on top */
$total = imap_num_msg($imap);
/* for every email... */
for( $i = $total; $i >= 1; $i--) {
$headers = imap_header($imap, $i);
$from = $headers->from[0]->mailbox . "@" . $headers->from[0]->host;
echo $from . "\n";
imap_delete($imap,$i);
imap_mail_move($imap,"$i:$i", "[Gmail]/Trash"); // Change or remove this line if you are not connecting to gmail. The path to the Trash folder in your Gmail may be different, capitalization is relevant.
}
}else{
echo "no emails";
}
/* close the connection */
imap_expunge($imap);
imap_close($imap);
function save_attachment( $content , $filename , $localfilepath, $thumbfilepath ) {
if (imap_base64($content) != FALSE) {
$file = fopen($localfilepath.$filename, 'w');
fwrite($file, imap_base64($content));
fclose($file);
}
}
?>
</code></pre>
| 3 | 2012-10-18T13:59:06Z | [
"php",
"python",
"gmail",
"attachment"
]
|
Fetching attachments from gmail via either python or php | 312,284 | <p>I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail">How can I download all emails with attachments from Gmail?</a></li>
</ul>
| 7 | 2008-11-23T08:03:16Z | 30,915,656 | <pre><code>I recently worked on this topic and here is the code which works well. It also saves the details of the attachments in a word document with the following details:
-> Date
-> Time
-> From
-> Email ID
-> Subject
<?php
/*
* Gmail attachment extractor.
*
* Downloads attachments from Gmail and saves it to a file.
* Uses PHP IMAP extension, so make sure it is enabled in your php.ini,
* extension=php_imap.dll
*
*/
header('Content-type:application\msword');
header('Content-Disposition:attachment;Filename=document_name.doc');
set_time_limit(0);
/* connect to gmail with your credentials */
$hostname = '{imap.googlemail.com:993/imap/ssl}INBOX';
$username = 'email@gmail.com';
$password = 'password';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to
Gmail: ' . imap_last_error());
/* get all new emails. If set to 'ALL' instead
* of 'NEW' retrieves all the emails, but can be
* resource intensive, so the following variable,
* $max_emails, puts the limit on the number of emails downloaded.
*
*/
$emails = imap_search($inbox,'ALL');
/* useful only if the above search is set to 'ALL' */
$max_emails = 110;
/* if any emails found, iterate through each email */
if($emails){
$count = 1;
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number){
/* get information specific to this email */
//$overview = imap_fetch_overview($inbox,$email_number,0);
$check=imap_check($inbox);
$result=imap_fetch_overview($inbox,"1:{$check->Nmsgs}",0);
foreach($result as $overview){
echo "#{$overview->msgno}({$overview->date})-From: {$overview->from}
{$overview->subject}\n"}
/* get mail message */
$message = imap_fetchbody($inbox,$email_number,2);
/* get mail structure */
$structure =imap_fetchstructure($inbox, $email_number);
//$functions = array('function1' => imap_fetchstructure($inbox,
$email_number));
//print_r(array_keys($functions));
$attachments = array();
//print_r(array_keys($attachments[$i]));
if($structure->parts[$i]->ifdparameters){
foreach($structure->parts[$i]->dparameters as $object){
if(strtolower($object->attribute) == 'filename'){
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']){
$attachments[$i]['attachment']imap_fetchbody($inbox,$email_number,$i+1);
/* 4 = QUOTED-PRINTABLE encoding */
if($structure->parts[$i]->encoding == 3){
$attachments[$i]['attachment'] = base64_decode($attachments[$i]
['attachment']);
}
/* 3 = BASE64 encoding */
elseif($structure->parts[$i]->encoding == 4){
$attachments[$i]['attachment'] =
quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
/* iterate through each attachment and save it */
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1){
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
/* prefix the email number to the filename in case two emails
* have the attachment with the same file name.
*/
$fp = fopen($email_number . "-" . $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
if($count++ >= $max_emails) break;
}
}
/* close the connection */
imap_close($inbox);
?>
</code></pre>
| 0 | 2015-06-18T12:42:16Z | [
"php",
"python",
"gmail",
"attachment"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 312,464 | <p>Here's a generator that yields the chunks you want:</p>
<pre><code>def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
</code></pre>
<hr>
<pre><code>import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74]]
</code></pre>
<hr>
<p>If you're using Python 2, you should use <code>xrange()</code> instead of <code>range()</code>:</p>
<pre><code>def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in xrange(0, len(l), n):
yield l[i:i + n]
</code></pre>
<hr>
<p>Also you can simply use list comprehension instead of write a function. Python 3:</p>
<pre><code>[l[i:i + n] for i in range(0, len(l), n)]
</code></pre>
<p>Python 2 version:</p>
<pre><code>[l[i:i + n] for i in xrange(0, len(l), n)]
</code></pre>
| 1,227 | 2008-11-23T12:33:53Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 312,466 | <p>If you know list size:</p>
<pre><code>def SplitList(list, chunk_size):
return [list[offs:offs+chunk_size] for offs in range(0, len(list), chunk_size)]
</code></pre>
<p>If you don't (an iterator):</p>
<pre><code>def IterChunks(sequence, chunk_size):
res = []
for item in sequence:
res.append(item)
if len(res) >= chunk_size:
yield res
res = []
if res:
yield res # yield the last, incomplete, portion
</code></pre>
<p>In the latter case, it can be rephrased in a more beautiful way if you can be sure that the sequence always contains a whole number of chunks of given size (i.e. there is no incomplete last chunk).</p>
| 8 | 2008-11-23T12:40:39Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 312,467 | <p>Here is a generator that work on arbitrary iterables:</p>
<pre><code>def split_seq(iterable, size):
it = iter(iterable)
item = list(itertools.islice(it, size))
while item:
yield item
item = list(itertools.islice(it, size))
</code></pre>
<p>Example:</p>
<pre><code>>>> import pprint
>>> pprint.pprint(list(split_seq(xrange(75), 10)))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74]]
</code></pre>
| 56 | 2008-11-23T12:41:37Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 312,472 | <p>heh, one line version</p>
<pre><code>In [48]: chunk = lambda ulist, step: map(lambda i: ulist[i:i+step], xrange(0, len(ulist), step))
In [49]: chunk(range(1,100), 10)
Out[49]:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
[51, 52, 53, 54, 55, 56, 57, 58, 59, 60],
[61, 62, 63, 64, 65, 66, 67, 68, 69, 70],
[71, 72, 73, 74, 75, 76, 77, 78, 79, 80],
[81, 82, 83, 84, 85, 86, 87, 88, 89, 90],
[91, 92, 93, 94, 95, 96, 97, 98, 99]]
</code></pre>
| 3 | 2008-11-23T12:51:16Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 312,644 | <p>Directly from the (old) Python documentation (recipes for itertools):</p>
<pre><code>from itertools import izip, chain, repeat
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
</code></pre>
<p>The current version, as suggested by J.F.Sebastian:</p>
<pre><code>from itertools import izip_longest # for Python 2.x
#from itertools import zip_longest # for Python 3.x
#from six.moves import zip_longest # for both (uses the six compat library)
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
</code></pre>
<p>I guess Guido's time machine worksâworkedâwill workâwill have workedâwas working again.</p>
<p>These solutions work because <code>[iter(iterable)]*n</code> (or the equivalent in the earlier version) creates <em>one</em> iterator, repeated <code>n</code> times in the list. <code>izip_longest</code> then effectively performs a round-robin of "each" iterator; because this is the same iterator, it is advanced by each such call, resulting in each such zip-roundrobin generating one tuple of <code>n</code> items.</p>
| 204 | 2008-11-23T15:48:53Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 314,771 | <pre><code>def split_seq(seq, num_pieces):
start = 0
for i in xrange(num_pieces):
stop = start + len(seq[i::num_pieces])
yield seq[start:stop]
start = stop
</code></pre>
<p>usage:</p>
<pre><code>seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for seq in split_seq(seq, 3):
print seq
</code></pre>
| 5 | 2008-11-24T16:56:57Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 319,970 | <pre><code>def chunk(lst):
out = []
for x in xrange(2, len(lst) + 1):
if not len(lst) % x:
factor = len(lst) / x
break
while lst:
out.append([lst.pop(0) for x in xrange(factor)])
return out
</code></pre>
| 2 | 2008-11-26T07:24:49Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 1,668,586 | <pre><code>>>> f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
>>> f("Hallo Welt", 3)
['Hal', 'lo ', 'Wel', 't']
>>>
</code></pre>
<p>If you are into brackets - I picked up a book on Erlang :)</p>
| 2 | 2009-11-03T16:45:31Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 1,751,478 | <p>If you want something super simple:</p>
<pre><code>def chunks(l, n):
n = max(1, n)
return (l[i:i+n] for i in xrange(0, len(l), n))
</code></pre>
| 409 | 2009-11-17T20:17:16Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 2,270,932 | <p>Without calling len() which is good for large lists:</p>
<pre><code>def splitter(l, n):
i = 0
chunk = l[:n]
while chunk:
yield chunk
i += n
chunk = l[i:i+n]
</code></pre>
<p>And this is for iterables:</p>
<pre><code>def isplitter(l, n):
l = iter(l)
chunk = list(islice(l, n))
while chunk:
yield chunk
chunk = list(islice(l, n))
</code></pre>
<p>The functional flavour of the above:</p>
<pre><code>def isplitter2(l, n):
return takewhile(bool,
(tuple(islice(start, n))
for start in repeat(iter(l))))
</code></pre>
<p>OR:</p>
<pre><code>def chunks_gen_sentinel(n, seq):
continuous_slices = imap(islice, repeat(iter(seq)), repeat(0), repeat(n))
return iter(imap(tuple, continuous_slices).next,())
</code></pre>
<p>OR:</p>
<pre><code>def chunks_gen_filter(n, seq):
continuous_slices = imap(islice, repeat(iter(seq)), repeat(0), repeat(n))
return takewhile(bool,imap(tuple, continuous_slices))
</code></pre>
| 2 | 2010-02-16T05:49:47Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 3,125,186 | <pre><code>def chunk(input, size):
return map(None, *([iter(input)] * size))
</code></pre>
| 38 | 2010-06-26T19:10:07Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 3,226,719 | <p>Simple yet elegant</p>
<pre><code>l = range(1, 1000)
print [l[x:x+10] for x in xrange(0, len(l), 10)]
</code></pre>
<p>or if you prefer:</p>
<pre><code>chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)]
chunks(l, 10)
</code></pre>
| 25 | 2010-07-12T07:58:43Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 5,711,993 | <p>If you had a chunk size of 3 for example, you could do:</p>
<pre><code>zip(*[iterable[i::3] for i in range(3)])
</code></pre>
<p>source:
<a href="http://code.activestate.com/recipes/303060-group-a-list-into-sequential-n-tuples/">http://code.activestate.com/recipes/303060-group-a-list-into-sequential-n-tuples/</a></p>
<p>I would use this when my chunk size is fixed number I can type, e.g. '3', and would never change.</p>
| 11 | 2011-04-19T05:27:19Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 5,872,632 | <p>Consider using <a href="http://matplotlib.sourceforge.net/" rel="nofollow">matplotlib.cbook</a> pieces</p>
<p>for example:</p>
<pre><code>import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
print s
</code></pre>
| 4 | 2011-05-03T16:27:37Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 9,255,750 | <pre><code>def chunks(iterable,n):
"""assumes n is an integer>0
"""
iterable=iter(iterable)
while True:
result=[]
for i in range(n):
try:
a=next(iterable)
except StopIteration:
break
else:
result.append(a)
if result:
yield result
else:
break
g1=(i*i for i in range(10))
g2=chunks(g1,3)
print g2
'<generator object chunks at 0x0337B9B8>'
print list(g2)
'[[0, 1, 4], [9, 16, 25], [36, 49, 64], [81]]'
</code></pre>
| 2 | 2012-02-13T04:50:38Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 12,150,728 | <p>I realise this question is old (stumbled over it on Google), but surely something like the following is far simpler and clearer than any of the huge complex suggestions and only uses slicing:</p>
<pre><code>def chunker(iterable, chunksize):
for i,c in enumerate(iterable[::chunksize]):
yield iterable[i*chunksize:(i+1)*chunksize]
>>> for chunk in chunker(range(0,100), 10):
... print list(chunk)
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
... etc ...
</code></pre>
| 3 | 2012-08-27T22:58:05Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 13,756,402 | <p>No one use tee() function under itertools ?</p>
<p><a href="http://docs.python.org/2/library/itertools.html#itertools.tee" rel="nofollow">http://docs.python.org/2/library/itertools.html#itertools.tee</a></p>
<pre><code>>>> import itertools
>>> itertools.tee([1,2,3,4,5,6],3)
(<itertools.tee object at 0x02932DF0>, <itertools.tee object at 0x02932EB8>, <itertools.tee object at 0x02932EE0>)
</code></pre>
<p>This will split list to 3 iterator , loop the iterator will get the sublist with equal length</p>
| -2 | 2012-12-07T03:16:51Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 14,937,534 | <p>See <a href="http://docs.python.org/3.3/library/functions.html?highlight=zip#zip" rel="nofollow">this reference</a></p>
<pre><code>>>> orange = range(1, 1001)
>>> otuples = list( zip(*[iter(orange)]*10))
>>> print(otuples)
[(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), ... (991, 992, 993, 994, 995, 996, 997, 998, 999, 1000)]
>>> olist = [list(i) for i in otuples]
>>> print(olist)
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ..., [991, 992, 993, 994, 995, 996, 997, 998, 999, 1000]]
>>>
</code></pre>
<p>Python3</p>
| 2 | 2013-02-18T13:31:51Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 16,004,505 | <p>A generator expression:</p>
<pre><code>def chunks(seq, n):
return (seq[i:i+n] for i in xrange(0, len(seq), n))
</code></pre>
<p>eg.</p>
<pre><code>print list(chunks(range(1, 1000), 10))
</code></pre>
| 8 | 2013-04-14T21:26:06Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 16,315,158 | <p><a href="http://pythonhosted.org/more-itertools/api.html#more_itertools.chunked">more-itertools has a chunks iterator.</a></p>
<p>It also has a lot more things, including all the recipes in the itertools documentation.</p>
| 14 | 2013-05-01T08:42:21Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 16,760,646 | <p>using List Comprehensions of python</p>
<pre><code>[range(t,t+10) for t in range(1,1000,10)]
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30],....
....[981, 982, 983, 984, 985, 986, 987, 988, 989, 990],
[991, 992, 993, 994, 995, 996, 997, 998, 999, 1000]]
</code></pre>
<p>visit <a href="http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">this link</a> to know about List Comprehensions</p>
| 0 | 2013-05-26T15:18:42Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 16,935,535 | <p>I know this is kind of old but I don't why nobody mentioned <code>numpy.array_split</code>:</p>
<pre><code>lst = range(50)
In [26]: np.array_split(b,5)
Out[26]:
[array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),
array([20, 21, 22, 23, 24, 25, 26, 27, 28, 29]),
array([30, 31, 32, 33, 34, 35, 36, 37, 38, 39]),
array([40, 41, 42, 43, 44, 45, 46, 47, 48, 49])]
</code></pre>
| 35 | 2013-06-05T08:54:26Z | [
"python",
"list",
"split",
"chunks"
]
|
How do you split a list into evenly sized chunks? | 312,443 | <p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p>
<p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p>
<p>This should work:</p>
<pre><code>l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]
</code></pre>
<p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p>
<p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most âpythonicâ way to iterate over a list in chunks?</a></p>
| 959 | 2008-11-23T12:15:52Z | 16,970,117 | <p>Not exactly the same but still nice</p>
<pre><code>def chunks(l, chunks):
return zip(*[iter(l)]*chunks)
l = range(1, 1000)
print chunks(l, 10) -> [ ( 1..10 ), ( 11..20 ), .., ( 991..999 ) ]
</code></pre>
| 1 | 2013-06-06T19:01:51Z | [
"python",
"list",
"split",
"chunks"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.