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 decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
11,651,279
<p>My solution:</p> <pre><code>def seq(start, stop, step=1, digit=0): x = float(start) v = [] while x &lt;= stop: v.append(round(x,digit)) x += step return v </code></pre>
1
2012-07-25T13:50:47Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
12,310,785
<pre><code>import numpy as np for i in np.arange(0, 1, 0.1): print i </code></pre>
7
2012-09-07T02:01:56Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
13,286,671
<p>Here's a solution using <a href="http://docs.python.org/2/library/itertools.html" rel="nofollow">itertools</a>:</p> <pre><code>import itertools def seq(start, end, step): assert(step != 0) sample_count = abs(end - start) / step return itertools.islice(itertools.count(start, step), sample_count) </code></pre> <p><strong>Usage Example:</strong></p> <pre><code>for i in seq(0, 1, 0.1): print i </code></pre> <p><strong>Output:</strong></p> <pre><code>0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 </code></pre>
6
2012-11-08T10:00:02Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
13,849,808
<p>My versions use the original range function to create multiplicative indices for the shift. This allows same syntax to the original range function. I have made two versions, one using float, and one using Decimal, because I found that in some cases I wanted to avoid the roundoff drift introduced by the floating point arithmetic.</p> <p>It is consistent with empty set results as in range/xrange.</p> <p>Passing only a single numeric value to either function will return the standard range output to the integer ceiling value of the input parameter (so if you gave it 5.5, it would return range(6).)</p> <p><strong>Edit: the code below is now available as package on pypi: <a href="http://pypi.python.org/pypi/Franges" rel="nofollow">Franges</a></strong></p> <pre><code>## frange.py from math import ceil # find best range function available to version (2.7.x / 3.x.x) try: _xrange = xrange except NameError: _xrange = range def frange(start, stop = None, step = 1): """frange generates a set of floating point values over the range [start, stop) with step size step frange([start,] stop [, step ])""" if stop is None: for x in _xrange(int(ceil(start))): yield x else: # create a generator expression for the index values indices = (i for i in _xrange(0, int((stop-start)/step))) # yield results for i in indices: yield start + step*i ## drange.py import decimal from math import ceil # find best range function available to version (2.7.x / 3.x.x) try: _xrange = xrange except NameError: _xrange = range def drange(start, stop = None, step = 1, precision = None): """drange generates a set of Decimal values over the range [start, stop) with step size step drange([start,] stop, [step [,precision]])""" if stop is None: for x in _xrange(int(ceil(start))): yield x else: # find precision if precision is not None: decimal.getcontext().prec = precision # convert values to decimals start = decimal.Decimal(start) stop = decimal.Decimal(stop) step = decimal.Decimal(step) # create a generator expression for the index values indices = ( i for i in _xrange( 0, ((stop-start)/step).to_integral_value() ) ) # yield results for i in indices: yield float(start + step*i) ## testranges.py import frange import drange list(frange.frange(0, 2, 0.5)) # [0.0, 0.5, 1.0, 1.5] list(drange.drange(0, 2, 0.5, precision = 6)) # [0.0, 0.5, 1.0, 1.5] list(frange.frange(3)) # [0, 1, 2] list(frange.frange(3.5)) # [0, 1, 2, 3] list(frange.frange(0,10, -1)) # [] </code></pre>
4
2012-12-12T22:29:48Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
14,224,256
<p>Here is my solution which works fine with float_range(-1, 0, 0.01) and works without floating point representation errors. It is not very fast, but works fine: </p> <pre><code>from decimal import Decimal def get_multiplier(_from, _to, step): digits = [] for number in [_from, _to, step]: pre = Decimal(str(number)) % 1 digit = len(str(pre)) - 2 digits.append(digit) max_digits = max(digits) return float(10 ** (max_digits)) def float_range(_from, _to, step, include=False): """Generates a range list of floating point values over the Range [start, stop] with step size step include=True - allows to include right value to if possible !! Works fine with floating point representation !! """ mult = get_multiplier(_from, _to, step) # print mult int_from = int(round(_from * mult)) int_to = int(round(_to * mult)) int_step = int(round(step * mult)) # print int_from,int_to,int_step if include: result = range(int_from, int_to + int_step, int_step) result = [r for r in result if r &lt;= int_to] else: result = range(int_from, int_to, int_step) # print result float_result = [r / mult for r in result] return float_result print float_range(-1, 0, 0.01,include=False) assert float_range(1.01, 2.06, 5.05 % 1, True) ==\ [1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01, 2.06] assert float_range(1.01, 2.06, 5.05 % 1, False)==\ [1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01] </code></pre>
0
2013-01-08T21:21:33Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
19,307,296
<p>I am only a beginner, but I had the same problem, when simulating some calculations. Here is how I attempted to work this out, which seems to be working with decimal steps.</p> <p>I am also quite lazy and so I found it hard to write my own range function.</p> <p>Basically what I did is changed my <code>xrange(0.0, 1.0, 0.01)</code> to <code>xrange(0, 100, 1)</code> and used the division by <code>100.0</code> inside the loop. I was also concerned, if there will be rounding mistakes. So I decided to test, whether there are any. Now I heard, that if for example <code>0.01</code> from a calculation isn't exactly the float <code>0.01</code> comparing them should return False (if I am wrong, please let me know).</p> <p>So I decided to test if my solution will work for my range by running a short test:</p> <pre><code>for d100 in xrange(0, 100, 1): d = d100 / 100.0 fl = float("0.00"[:4 - len(str(d100))] + str(d100)) print d, "=", fl , d == fl </code></pre> <p>And it printed True for each.</p> <p>Now, if I'm getting it totally wrong, please let me know.</p>
0
2013-10-10T22:27:18Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
20,101,849
<p>This one liner will not clutter your code. The sign of the <strong>step</strong> parameter is important.</p> <pre><code>def frange(start, stop, step): return [x*step+start for x in range(0,round(abs((stop-start)/step)+0.5001), int((stop-start)/step&lt;0)*-2+1)] </code></pre>
0
2013-11-20T16:47:50Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
20,549,652
<p>This is my solution to get ranges with float steps. <br>Using this function it's not necessary to import numpy, nor install it. <br>I'm pretty sure that it could be improved and optimized. Feel free to do it and post it here.</p> <pre><code>from __future__ import division from math import log def xfrange(start, stop, step): old_start = start #backup this value digits = int(round(log(10000, 10)))+1 #get number of digits magnitude = 10**digits stop = int(magnitude * stop) #convert from step = int(magnitude * step) #0.1 to 10 (e.g.) if start == 0: start = 10**(digits-1) else: start = 10**(digits)*start data = [] #create array #calc number of iterations end_loop = int((stop-start)//step) if old_start == 0: end_loop += 1 acc = start for i in xrange(0, end_loop): data.append(acc/magnitude) acc += step return data print xfrange(1, 2.1, 0.1) print xfrange(0, 1.1, 0.1) print xfrange(-1, 0.1, 0.1) </code></pre> <p>The output is:</p> <pre><code>[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0] [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1] [-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0] </code></pre>
3
2013-12-12T17:04:50Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
23,715,956
<p><code>scipy</code> has a built in function <code>arange</code> which generalizes Python's <code>range()</code> constructor to satisfy your requirement of float handling. </p> <p><code>from scipy import arange</code></p>
16
2014-05-17T20:50:03Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
24,683,593
<p>frange(start, stop, precision)</p> <pre><code>def frange(a,b,i): p = 10**i sr = a*p er = (b*p) + 1 p = float(p) return map(lambda x: x/p, xrange(sr,er)) In &gt;frange(-1,1,1) Out&gt;[-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] </code></pre>
0
2014-07-10T18:15:39Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
32,347,033
<p>The trick to avoid <em>round-off problem</em> is to use a separate number to move through the range, that starts and <em>half</em> the <em>step</em> ahead of <em>start</em>.</p> <pre><code># floating point range def frange(a, b, stp=1.0): i = a+stp/2.0 while i&lt;b: yield a a += stp i += stp </code></pre> <p>Alternatively, <code>numpy.arange</code> can be used.</p>
1
2015-09-02T07:28:42Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
32,536,460
<p>For completeness of boutique, a functional solution:</p> <pre><code>def frange(a,b,s): return [] if s &gt; 0 and a &gt; b or s &lt; 0 and a &lt; b or s==0 else [a]+frange(a+s,b,s) </code></pre>
3
2015-09-12T07:44:22Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
35,362,489
<p>It can be done using Numpy library. arange() function allows steps in float. But, it returns a numpy array which can be converted to list using tolist() for our convenience.</p> <pre><code>for i in np.arange(0, 1, 0.1).tolist(): print i </code></pre>
0
2016-02-12T12:18:12Z
[ "python", "floating-point", "range" ]
Easy_install of wxpython has "setup script" error
477,573
<p>I have an install of python 2.5 that fink placed in /sw/bin/. I use the easy install command</p> <pre><code>sudo /sw/bin/easy_install wxPython </code></pre> <p>to try to install wxpython and I get an error while trying to process wxPython-src-2.8.9.1.tab.bz2 that there is not setup script. Easy-install has worked for several other installations until this one. Any help on why it's busting now?</p> <p>EDIT: The error occurs before dumping back to shell prompt.</p> <p><i>Reading <a href="http://wxPython.org/download.php">http://wxPython.org/download.php</a><br> Best match: wxPython src-2.8.9.1<br> Downloading <a href="http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.9.1.tar.bz2">http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.9.1.tar.bz2</a><br> Processing wxPython-src-2.8.9.1.tar.bz2 <br> error: Couldn't find a setup script in /tmp/easy_install-tNg6FG/wxPython-src-2.8.9.1.tar.bz2 </i></p>
11
2009-01-25T11:25:02Z
478,200
<p>There is a simple reason why it's busting: there just is no setup.py in wxPython; wxPython does not use distutils for installation.</p> <p>Instead, read the file README.1st.txt in source distribution for instruction on how to install wxPython.</p>
9
2009-01-25T20:19:45Z
[ "python", "wxpython", "easy-install" ]
Easy_install of wxpython has "setup script" error
477,573
<p>I have an install of python 2.5 that fink placed in /sw/bin/. I use the easy install command</p> <pre><code>sudo /sw/bin/easy_install wxPython </code></pre> <p>to try to install wxpython and I get an error while trying to process wxPython-src-2.8.9.1.tab.bz2 that there is not setup script. Easy-install has worked for several other installations until this one. Any help on why it's busting now?</p> <p>EDIT: The error occurs before dumping back to shell prompt.</p> <p><i>Reading <a href="http://wxPython.org/download.php">http://wxPython.org/download.php</a><br> Best match: wxPython src-2.8.9.1<br> Downloading <a href="http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.9.1.tar.bz2">http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.9.1.tar.bz2</a><br> Processing wxPython-src-2.8.9.1.tar.bz2 <br> error: Couldn't find a setup script in /tmp/easy_install-tNg6FG/wxPython-src-2.8.9.1.tar.bz2 </i></p>
11
2009-01-25T11:25:02Z
3,042,520
<p><strong>wxPython 2.8.9.1 does use distutils</strong></p> <p>Under 'wxPython-src-2.8.9.1/wxPython/' run:</p> <pre><code>sudo python setup.py install </code></pre> <p>To install wxPython. At least that's what the INSTALL.txt says for that specific version.</p>
3
2010-06-15T04:34:54Z
[ "python", "wxpython", "easy-install" ]
What's the idiomatic Python equivalent to Django's 'regroup' template tag?
477,820
<p><a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup</a></p> <p>I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner.</p>
12
2009-01-25T15:29:44Z
477,839
<p>Combine <a href="http://docs.python.org/library/itertools.html#itertools.groupby"><code>itertools.groupby</code></a> with <a href="http://docs.python.org/library/operator.html#operator.itemgetter"><code>operator.itemgetter</code></a> to get a pretty nice solution:</p> <pre><code>from operator import itemgetter from itertools import groupby key = itemgetter('gender') iter = groupby(sorted(people, key=key), key=key) for gender, people in iter: print '===', gender, '===' for person in people: print person </code></pre>
26
2009-01-25T15:43:26Z
[ "python", "django", "django-templates" ]
What's the idiomatic Python equivalent to Django's 'regroup' template tag?
477,820
<p><a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup</a></p> <p>I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner.</p>
12
2009-01-25T15:29:44Z
28,368,652
<p>If the source of data (<code>people</code> in this case) is already sorted by the key, you can bypass the <code>sorted</code> call:</p> <pre><code>iter = groupby(people, key=lambda x:x['gender']) for gender, people in iter: print '===', gender, '===' for person in people: print person </code></pre> <p>Note: If <code>sorted</code> is a common dictionary, there are no guarantees of order; therefore you must call <code>sorted</code>. Here I'm supposing that <code>sorted</code> is a <code>collections.OrderedDict</code> or some other kind of ordered data structure.</p>
0
2015-02-06T15:04:07Z
[ "python", "django", "django-templates" ]
What's the idiomatic Python equivalent to Django's 'regroup' template tag?
477,820
<p><a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup</a></p> <p>I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner.</p>
12
2009-01-25T15:29:44Z
30,701,291
<p>Previous answers helped me to solve my problem. For future reference, if you have some nested data like </p> <blockquote> <p>{'city_name': 'City1', 'comp_name': 'Company1', 'name': 'Branch1'}</p> </blockquote> <p>and you want to group by City and then by Company in that city like:</p> <pre><code>City1 Company 1 Branch 1 Branch 2 Company 2 Branch 1 Company 3 Branch 1 City2 Company 2 Branch 1 Company 3 Branch 1 Branch 2 City3 Company 1 Branch 1 Company 2 Branch 1 Branch 2 </code></pre> <p>I solved it by doing this:</p> <pre><code>key = itemgetter('city_name') iter = groupby(queryset, key=key) # assuming queryset is already sorted by city_name for key, group in iter: print(key) key2 = itemgetter('company_name') iter2 = groupby(sorted(group, key=key2), key=key2) # now we must sort by company_name for comp, branch in iter2: print(comp) for b in branch: print(b) </code></pre>
1
2015-06-08T04:34:08Z
[ "python", "django", "django-templates" ]
Python and os.chroot
478,359
<p>I'm writing a web-server in Python as a hobby project. The code is targeted at *NIX machines. I'm new to developing on Linux and even newer to Python itself.</p> <p>I am worried about people breaking out of the folder that I'm using to serve up the web-site. The most obvious way to do this is to filter requests for documents like /../../etc/passwd. However, I'm worried that there might be clever ways to go up the directory tree that I'm not aware of and consequentially my filter won't catch. </p> <p>I'm considering adding using the os.chroot so that the root directory is the web-site itself. Is this is a safe way of protecting against these jail breaking attacks? Are there any potential pitfalls to doing this that will hurt me down the road?</p>
2
2009-01-25T21:39:22Z
478,396
<p>Yes there are pitfalls. Security wise:</p> <ol> <li>If you run as root, there are always ways to break out. So first chroot(), then PERMANENTLY drop privileges to an other user.</li> <li>Put nothing which isn't absolutely required into the chroot tree. Especially no suid/sgid files, named pipes, unix domain sockets and device nodes.</li> </ol> <p>Python wise your whole module loading gets screwed up. Python is simply not made for such scenarios. If your application is moderately complex you <em>will</em> run into module loading issues.</p> <p>I think much more important than chrooting is running as a non privileged user and simply using the file system permissions to keep that user from reading anything of importance.</p>
7
2009-01-25T22:02:05Z
[ "python", "linux", "chroot" ]
Python and os.chroot
478,359
<p>I'm writing a web-server in Python as a hobby project. The code is targeted at *NIX machines. I'm new to developing on Linux and even newer to Python itself.</p> <p>I am worried about people breaking out of the folder that I'm using to serve up the web-site. The most obvious way to do this is to filter requests for documents like /../../etc/passwd. However, I'm worried that there might be clever ways to go up the directory tree that I'm not aware of and consequentially my filter won't catch. </p> <p>I'm considering adding using the os.chroot so that the root directory is the web-site itself. Is this is a safe way of protecting against these jail breaking attacks? Are there any potential pitfalls to doing this that will hurt me down the road?</p>
2
2009-01-25T21:39:22Z
478,501
<p>Check out <a href="http://twistedmatrix.com" rel="nofollow">Twisted</a>. <code>twistd</code> supports privilege shedding and chroot operation out of the box. Additionally it has a whole framework for writing network services, daemons, and pretty much everything.</p>
3
2009-01-25T23:15:25Z
[ "python", "linux", "chroot" ]
How to send multiple input field values with same name?
478,382
<p>I have m2m field, lets say it have name 'relations', so i want to allow user to send as many relations as he wants. I add new input to html with javascript with same name, like so</p> <pre><code>&lt;input type='text' name='relations' value='a' /&gt; &lt;input type='text' name='relations' value='b' /&gt; </code></pre> <p>in cleaned_data i receive only value of second input ('b'). How to receive both?</p>
12
2009-01-25T21:55:12Z
478,406
<p>I don't know how to do that with Forms, but if you want to grab the values in the raw way, here's how I'd do:</p> <pre><code>relations = request.POST.getlist('relations') </code></pre>
20
2009-01-25T22:11:21Z
[ "python", "django", "django-forms" ]
How to send multiple input field values with same name?
478,382
<p>I have m2m field, lets say it have name 'relations', so i want to allow user to send as many relations as he wants. I add new input to html with javascript with same name, like so</p> <pre><code>&lt;input type='text' name='relations' value='a' /&gt; &lt;input type='text' name='relations' value='b' /&gt; </code></pre> <p>in cleaned_data i receive only value of second input ('b'). How to receive both?</p>
12
2009-01-25T21:55:12Z
478,989
<p>You don't need to grab all the raw values, you can just get the specific data by using element name like this:</p> <pre><code>relations = request.form.getlist('relations') </code></pre> <p>That will return a list of values in the <code>relations</code> input.</p>
4
2009-01-26T06:38:51Z
[ "python", "django", "django-forms" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
478,470
<p>There is a limit because it would take too much memory to store the complete state machine efficiently. I'd say that if you have more than 100 groups in your re, something is wrong either in the re itself or in the way you are using them. Maybe you need to split the input and work on smaller chunks or something.</p>
11
2009-01-25T22:54:05Z
[ "python", "regex" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
478,484
<p>I would say you could reduce the number of groups by using non-grouping parentheses, but whatever it is that you're doing seems like you want all these groupings.</p>
-1
2009-01-25T23:07:02Z
[ "python", "regex" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
478,849
<p>First, as others have said, there are probably good alternatives to using 100 groups. The <code>re.findall</code> method might be a useful place to start. If you really need more than 100 groups, the only workaround I see is to modify the core Python code. </p> <p>In <code>[python-install-dir]/lib/sre_compile.py</code> simply modify the <code>compile()</code> function by removing the following lines:</p> <pre><code># in lib/sre_compile.py if pattern.groups &gt; 100: raise AssertionError( "sorry, but this version only supports 100 named groups" ) </code></pre> <p>For a slightly more flexible version, just define a constant at the top of the <code>sre_compile</code> module, and have the above line compare to that constant instead of 100. </p> <p>Funnily enough, in the (Python 2.5) source there is a comment indicating that the 100 group limit is scheduled to be removed in future versions.</p>
2
2009-01-26T04:38:53Z
[ "python", "regex" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
481,549
<p>I'm not sure what you're doing exactly, but try using a single group, with a lot of OR clauses inside... so (this)|(that) becomes (this|that). You can do clever things with the results by passing a function that does something with the particular word that is matched:</p> <pre><code> newContents, num = cregex.subn(lambda m: replacements[m.string[m.start():m.end()]], contents) </code></pre> <p>If you really need so many groups, you'll probably have to do it in stages... one pass for a dozen big groups, then another pass inside each of those groups for all the details you want.</p>
2
2009-01-26T21:58:27Z
[ "python", "regex" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
2,909,184
<p>in my case, i have a dictionary of n words and want to create a single regex that matches all of them.. ie: if my dictionary is</p> <pre><code>hello goodbye </code></pre> <p>my regex would be: <code>(^|\s)hello($|\s)|(^|\s)goodbye($|\s)</code> ... it's the only way to do it, and works fine on small dictionaries, but when you have more tan 50 words, well... </p>
-1
2010-05-25T23:15:50Z
[ "python", "regex" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
10,798,598
<p>If I'm not mistaken, the "new" <a href="http://pypi.python.org/pypi/regex/" rel="nofollow">regex</a> module (currently third-party, but intended to eventually replace the re module in the stdlib) does not have this limit, so you might give that a try.</p>
3
2012-05-29T11:53:10Z
[ "python", "regex" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
13,458,403
<p>It's very ease to resolve this error: Open the <code>re</code> class and you'll see this constant <code>_MAXCACHE = 100</code>. Change the value to <code>1000</code>, for example, and do a test.</p>
-1
2012-11-19T16:49:41Z
[ "python", "regex" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
14,391,579
<p>I found the easiest way was to</p> <pre><code>import regex as re </code></pre> <p>instead of </p> <pre><code>import re </code></pre> <p>The default _MAXCACHE for regex is 500 instead of 100 I believe. This is one of the many reasons I find regex to be a better module than re.</p>
1
2013-01-18T02:37:06Z
[ "python", "regex" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
26,521,973
<p>When I run into this I had a really complex pattern that was actually composed of a bunch of high-level patterns joined by ORs, like this:</p> <pre><code>pattern_string = u"pattern1|" \ u"pattern2|" \ u"patternN" pattern = re.compile(pattern_string, re.UNICODE) for match in pattern.finditer(string_to_search): pass # Extract data from the groups in the match. </code></pre> <p>As a workaround, I turned the pattern into a list and I used that list as follows:</p> <pre><code>pattern_strings = [ u"pattern1", u"pattern2", u"patternN", ] patterns = [re.compile(pattern_string, re.UNICODE) for pattern_string in pattern_strings] for pattern in patterns: for match in pattern.finditer(string_to_search): pass # Extract data from the groups in the match. string_to_search = pattern.sub(u"", string_to_search) </code></pre>
0
2014-10-23T05:45:39Z
[ "python", "regex" ]
Python regular expressions with more than 100 groups?
478,458
<p>Is there any way to beat the 100-group limit for regular expressions in Python? Also, could someone explain why there is a limit. Thanks.</p>
13
2009-01-25T22:48:56Z
34,046,296
<p>I doubt you really need to process 100 named groups by next commands or use it in <code>regexp</code> replacement command. It would be quite impractical. If you just need groups to express the rich conditions in <code>regexp</code> you can use non-grouping group. </p> <pre><code>(?:word1|word2)(?:word3|word4) </code></pre> <p>etc. Complex scenarios including nesting groups are possible. There is no limit for non-grouping groups.</p>
3
2015-12-02T15:17:13Z
[ "python", "regex" ]
Need to route instance calls inside a python class
478,655
<p>The problem is a need to take the arguments into account before choosing the responder. Here is my attempt so far.</p> <pre><code>from responders import A, B, C class RandomResponder(object) def init(self, *args, *kwargs): self.args = args self.kwargs = kwargs def __getattr__(self, name): # pick a responder based on the args the function was called with # I don't know how to do this part # for sake of argument lets the args a function was called with lead me to pick responder A r = A responder = r(*self.args, **self.kwargs) return responder.__getattr__(name) </code></pre> <p>The desired effect would be:</p> <pre><code>r = RandomResponder() r.doSomething(1) #returns A.doSomething() r.doSomething(2) #returns B.doSomething() r.doSomething(3) #return C.doSomething() r.doSomethingElse(1) #returns A.doSomethingElse() r.doSomethingElse(2) #returns B.doSomethingElse() r.doSomethingElse(3) #returns C.doSomethingElse() </code></pre> <p>I will not know ahead of time all the functions contained with the responders A, B, and C.</p>
1
2009-01-26T01:45:01Z
478,673
<p>If you specify <code>args</code> (without the asterisk), it's just a List of values (strings). Similarly, <code>kwargs</code> is a Dict of matching keys (strings) to values (strings).</p> <p><a href="http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/" rel="nofollow">This</a> is one of the first results I found after Googling <a href="http://www.google.com/search?q=args+kwargs" rel="nofollow">args kwargs</a>.</p> <p>Edit: I actually don't know quite what you're looking for, so this is just a guess.</p>
0
2009-01-26T02:01:44Z
[ "python", "class", "instance" ]
Need to route instance calls inside a python class
478,655
<p>The problem is a need to take the arguments into account before choosing the responder. Here is my attempt so far.</p> <pre><code>from responders import A, B, C class RandomResponder(object) def init(self, *args, *kwargs): self.args = args self.kwargs = kwargs def __getattr__(self, name): # pick a responder based on the args the function was called with # I don't know how to do this part # for sake of argument lets the args a function was called with lead me to pick responder A r = A responder = r(*self.args, **self.kwargs) return responder.__getattr__(name) </code></pre> <p>The desired effect would be:</p> <pre><code>r = RandomResponder() r.doSomething(1) #returns A.doSomething() r.doSomething(2) #returns B.doSomething() r.doSomething(3) #return C.doSomething() r.doSomethingElse(1) #returns A.doSomethingElse() r.doSomethingElse(2) #returns B.doSomethingElse() r.doSomethingElse(3) #returns C.doSomethingElse() </code></pre> <p>I will not know ahead of time all the functions contained with the responders A, B, and C.</p>
1
2009-01-26T01:45:01Z
478,706
<p>Are you trying to do this?</p> <pre><code>from responders import A, B, C class RandomResponder(object) def pickAResponder( self, someName ): """Use a simple mapping.""" return { 'nameA': A, 'nameB': B, 'nameC': C }[someName] def __init__(self, *args, *kwargs): self.args = args self.kwargs = kwargs def __getattr__(self, name): """pick a responder based on the args[0]""" r = self.pickAResponder(self.args[0]) responder = r(*self.args, **self.kwargs) return responder.__getattr__(name) </code></pre> <p>Your responder classes (A, B, C) are just objects. You can manipulate a class using mappings, lists, if-statements, whatever Python coding you want in the <code>pickAResponder</code> method.</p>
0
2009-01-26T02:32:02Z
[ "python", "class", "instance" ]
Need to route instance calls inside a python class
478,655
<p>The problem is a need to take the arguments into account before choosing the responder. Here is my attempt so far.</p> <pre><code>from responders import A, B, C class RandomResponder(object) def init(self, *args, *kwargs): self.args = args self.kwargs = kwargs def __getattr__(self, name): # pick a responder based on the args the function was called with # I don't know how to do this part # for sake of argument lets the args a function was called with lead me to pick responder A r = A responder = r(*self.args, **self.kwargs) return responder.__getattr__(name) </code></pre> <p>The desired effect would be:</p> <pre><code>r = RandomResponder() r.doSomething(1) #returns A.doSomething() r.doSomething(2) #returns B.doSomething() r.doSomething(3) #return C.doSomething() r.doSomethingElse(1) #returns A.doSomethingElse() r.doSomethingElse(2) #returns B.doSomethingElse() r.doSomethingElse(3) #returns C.doSomethingElse() </code></pre> <p>I will not know ahead of time all the functions contained with the responders A, B, and C.</p>
1
2009-01-26T01:45:01Z
478,751
<p>What about:</p> <pre><code>RandomResponder = [A, B, C] RandomResponder[0].doSomething() # returns A.doSomething() RandomResponder[1].doSomething() # returns B.doSomething() RandomResponder[2].doSomething() # returns C.doSomething() # etc </code></pre>
1
2009-01-26T03:02:38Z
[ "python", "class", "instance" ]
Need to route instance calls inside a python class
478,655
<p>The problem is a need to take the arguments into account before choosing the responder. Here is my attempt so far.</p> <pre><code>from responders import A, B, C class RandomResponder(object) def init(self, *args, *kwargs): self.args = args self.kwargs = kwargs def __getattr__(self, name): # pick a responder based on the args the function was called with # I don't know how to do this part # for sake of argument lets the args a function was called with lead me to pick responder A r = A responder = r(*self.args, **self.kwargs) return responder.__getattr__(name) </code></pre> <p>The desired effect would be:</p> <pre><code>r = RandomResponder() r.doSomething(1) #returns A.doSomething() r.doSomething(2) #returns B.doSomething() r.doSomething(3) #return C.doSomething() r.doSomethingElse(1) #returns A.doSomethingElse() r.doSomethingElse(2) #returns B.doSomethingElse() r.doSomethingElse(3) #returns C.doSomethingElse() </code></pre> <p>I will not know ahead of time all the functions contained with the responders A, B, and C.</p>
1
2009-01-26T01:45:01Z
478,759
<p>When you do this</p> <pre><code>r.doSomething(1) </code></pre> <p>what happens is, in order:</p> <ul> <li><code>r.__getattr__</code> is called, and returns an object</li> <li>this object is called with an argument "1" </li> </ul> <p>At the time when <code>__getattr__</code> is called, you have no way of knowing what arguments the object you return is <em>going</em> to get called with, or even if it's going to be called at all... </p> <p>So, to get the behavior that you want, <code>__getattr__</code> has to return a callable object that makes the decision itself based on the arguments <em>it's</em> called with. For example</p> <pre><code>from responders import A, B, C class RandomResponder(object): def __getattr__(self, name): def func(*args, **kwds): resp = { 1:A, 2:B, 3:C }[args[0]] # Decide which responder to use (example) return getattr(resp, name)() # Call the function on the responder return func </code></pre>
3
2009-01-26T03:07:59Z
[ "python", "class", "instance" ]
Need to route instance calls inside a python class
478,655
<p>The problem is a need to take the arguments into account before choosing the responder. Here is my attempt so far.</p> <pre><code>from responders import A, B, C class RandomResponder(object) def init(self, *args, *kwargs): self.args = args self.kwargs = kwargs def __getattr__(self, name): # pick a responder based on the args the function was called with # I don't know how to do this part # for sake of argument lets the args a function was called with lead me to pick responder A r = A responder = r(*self.args, **self.kwargs) return responder.__getattr__(name) </code></pre> <p>The desired effect would be:</p> <pre><code>r = RandomResponder() r.doSomething(1) #returns A.doSomething() r.doSomething(2) #returns B.doSomething() r.doSomething(3) #return C.doSomething() r.doSomethingElse(1) #returns A.doSomethingElse() r.doSomethingElse(2) #returns B.doSomethingElse() r.doSomethingElse(3) #returns C.doSomethingElse() </code></pre> <p>I will not know ahead of time all the functions contained with the responders A, B, and C.</p>
1
2009-01-26T01:45:01Z
478,763
<p>Try this:</p> <pre><code>class RandomResponder(object): choices = [A, B, C] @classmethod def which(cls): return random.choice(cls.choices) def __getattr__(self, attr): return getattr(self.which(), attr) </code></pre> <p>which() randomly selects an option from the choices, and which <strong>getattr</strong> uses to get the attribute.</p> <p>EDIT: it actually looks like you want something more like this.</p> <pre><code>class RandomResponder(object): choices = [A, B, C] def __getattr__(self, attr): # we define a function that actually gets called # which takes up the first positional argument, # the rest are left to args and kwargs def doCall(which, *args, **kwargs): # get the attribute of the appropriate one, call with passed args return getattr(self.choices[which], attr)(*args, **kwargs) return doCall </code></pre> <p>This could be written using lambda, but I'll just leave it like this so it's clearer.</p>
2
2009-01-26T03:09:31Z
[ "python", "class", "instance" ]
is there a string method to capitalize acronyms in python?
479,043
<p>This is good:</p> <blockquote> <blockquote> <blockquote> <p>import string string.capwords("proper name") 'Proper Name'</p> </blockquote> </blockquote> </blockquote> <p>This is not so good: </p> <blockquote> <blockquote> <blockquote> <p>string.capwords("I.R.S") 'I.r.s'</p> </blockquote> </blockquote> </blockquote> <p>Is there no string method to do capwords so that it accomodates acronyms?</p>
0
2009-01-26T07:33:44Z
479,044
<p>No, there is no such method in the standard library.</p>
2
2009-01-26T07:36:00Z
[ "python", "string", "acronym", "capitalize" ]
is there a string method to capitalize acronyms in python?
479,043
<p>This is good:</p> <blockquote> <blockquote> <blockquote> <p>import string string.capwords("proper name") 'Proper Name'</p> </blockquote> </blockquote> </blockquote> <p>This is not so good: </p> <blockquote> <blockquote> <blockquote> <p>string.capwords("I.R.S") 'I.r.s'</p> </blockquote> </blockquote> </blockquote> <p>Is there no string method to do capwords so that it accomodates acronyms?</p>
0
2009-01-26T07:33:44Z
479,047
<p>Even if there were such a function, what would it do when asked to process "IRS"? Even the IRS call themselves "IRS" with no dots.</p>
1
2009-01-26T07:37:13Z
[ "python", "string", "acronym", "capitalize" ]
is there a string method to capitalize acronyms in python?
479,043
<p>This is good:</p> <blockquote> <blockquote> <blockquote> <p>import string string.capwords("proper name") 'Proper Name'</p> </blockquote> </blockquote> </blockquote> <p>This is not so good: </p> <blockquote> <blockquote> <blockquote> <p>string.capwords("I.R.S") 'I.r.s'</p> </blockquote> </blockquote> </blockquote> <p>Is there no string method to do capwords so that it accomodates acronyms?</p>
0
2009-01-26T07:33:44Z
479,082
<p>This might work:</p> <pre><code>import re def _callback(match): """ This is a simple callback function for the regular expression which is in charge of doing the actual capitalization. It is designed to only capitalize words which aren't fully uppercased (like acronyms). """ word = match.group(0) if word == word.upper(): return word else: return word.capitalize() def capwords(data): """ This function converts `data` into a capitalized version of itself. This function accomidates acronyms. """ return re.sub("[\w\'\-\_]+", _callback, data) </code></pre> <p>Here is a test:</p> <pre><code>print capwords("This is an IRS test.") # Produces: "This Is An IRS Test." print capwords("This is an I.R.S. test.") # Produces: "This Is An I.R.S. Test." </code></pre>
5
2009-01-26T08:08:40Z
[ "python", "string", "acronym", "capitalize" ]
is there a string method to capitalize acronyms in python?
479,043
<p>This is good:</p> <blockquote> <blockquote> <blockquote> <p>import string string.capwords("proper name") 'Proper Name'</p> </blockquote> </blockquote> </blockquote> <p>This is not so good: </p> <blockquote> <blockquote> <blockquote> <p>string.capwords("I.R.S") 'I.r.s'</p> </blockquote> </blockquote> </blockquote> <p>Is there no string method to do capwords so that it accomodates acronyms?</p>
0
2009-01-26T07:33:44Z
479,126
<p>I just used a list comprehension: [ ".".join( [ string.capwords(l) for l in entry.split(".") ] ) for entry in original_list ]</p>
-1
2009-01-26T08:38:23Z
[ "python", "string", "acronym", "capitalize" ]
How do I simulate biased die in python?
479,236
<p>I want to simulate N-sided biased die? </p> <pre><code>def roll(N,bias): '''this function rolls N dimensional die with biasing provided''' # do something return result &gt;&gt; N=6 &gt;&gt; bias=( 0.20,0.20,0.15,0.15,0.14,0.16,) &gt;&gt; roll(N,bias) 2 </code></pre>
3
2009-01-26T09:37:47Z
479,263
<p>More language agnostic, but you could use a lookup table.</p> <p>Use a random number in the range 0-1 and lookup the value in a table:</p> <pre><code>0.00 - 0.20 1 0.20 - 0.40 2 0.40 - 0.55 3 0.55 - 0.70 4 0.70 - 0.84 5 0.84 - 1.00 6 </code></pre>
6
2009-01-26T09:47:21Z
[ "python", "probability" ]
How do I simulate biased die in python?
479,236
<p>I want to simulate N-sided biased die? </p> <pre><code>def roll(N,bias): '''this function rolls N dimensional die with biasing provided''' # do something return result &gt;&gt; N=6 &gt;&gt; bias=( 0.20,0.20,0.15,0.15,0.14,0.16,) &gt;&gt; roll(N,bias) 2 </code></pre>
3
2009-01-26T09:37:47Z
479,299
<p>A little bit of math here.</p> <p>A regular die will give each number 1-6 with equal probability, namely <code>1/6</code>. This is referred to as <a href="http://en.wikipedia.org/wiki/Uniform_distribution">uniform distribution</a> (the discrete version of it, as opposed to the continuous version). Meaning that if <code>X</code> is a random variable describing the result of a single role then <code>X~U[1,6]</code> - meaning <code>X</code> is distributed equally against all possible results of the die roll, 1 through 6.</p> <p>This is equal to choosing a number in <code>[0,1)</code> while dividing it into 6 sections: <code>[0,1/6)</code>, <code>[1/6,2/6)</code>, <code>[2/6,3/6)</code>, <code>[3/6,4/6)</code>, <code>[4/6,5/6)</code>, <code>[5/6,1)</code>.</p> <p>You are requesting a different distribution, which is biased. The easiest way to achieve this is to divide the section <code>[0,1)</code> to 6 parts depending on the bias you want. So in your case you would want to divide it into the following: <code>[0,0.2)</code>, <code>[0.2,0.4)</code>, <code>[0.4,0.55)</code>, <code>0.55,0.7)</code>, <code>[0.7,0.84)</code>, <code>[0.84,1)</code>.</p> <p>If you take a look at the <a href="http://en.wikipedia.org/wiki/Uniform_distribution">wikipedia entry</a>, you will see that in this case, the cumulative probability function will not be composed of 6 equal-length parts but rather of 6 parts which differ in length according to the <em>bias</em> you gave them. Same goes for the mass distribution.</p> <p>Back to the question, depending on the language you are using, just translate this back to your die roll. In Python, here is a very sketchy, albeit working, example:</p> <pre><code>import random sampleMassDist = (0.2, 0.1, 0.15, 0.15, 0.25, 0.15) # assume sum of bias is 1 def roll(massDist): randRoll = random.random() # in [0,1) sum = 0 result = 1 for mass in massDist: sum += mass if randRoll &lt; sum: return result result+=1 print roll(sampleMassDist) </code></pre>
17
2009-01-26T10:09:03Z
[ "python", "probability" ]
How do I simulate biased die in python?
479,236
<p>I want to simulate N-sided biased die? </p> <pre><code>def roll(N,bias): '''this function rolls N dimensional die with biasing provided''' # do something return result &gt;&gt; N=6 &gt;&gt; bias=( 0.20,0.20,0.15,0.15,0.14,0.16,) &gt;&gt; roll(N,bias) 2 </code></pre>
3
2009-01-26T09:37:47Z
479,313
<pre><code>import random def roll(sides, bias_list): assert len(bias_list) == sides number = random.uniform(0, sum(bias_list)) current = 0 for i, bias in enumerate(bias_list): current += bias if number &lt;= current: return i + 1 </code></pre> <p>The bias will be proportional.</p> <pre><code>&gt;&gt;&gt; print roll(6, (0.20, 0.20, 0.15, 0.15, 0.14, 0.16)) 6 &gt;&gt;&gt; print roll(6, (0.20, 0.20, 0.15, 0.15, 0.14, 0.16)) 2 </code></pre> <p>Could use integers too (better):</p> <pre><code>&gt;&gt;&gt; print roll(6, (10, 1, 1, 1, 1, 1)) 5 &gt;&gt;&gt; print roll(6, (10, 1, 1, 1, 1, 1)) 1 &gt;&gt;&gt; print roll(6, (10, 1, 1, 1, 1, 1)) 1 &gt;&gt;&gt; print roll(6, (10, 5, 5, 10, 4, 8)) 2 &gt;&gt;&gt; print roll(6, (1,) * 6) 4 </code></pre>
4
2009-01-26T10:14:49Z
[ "python", "probability" ]
How do I simulate biased die in python?
479,236
<p>I want to simulate N-sided biased die? </p> <pre><code>def roll(N,bias): '''this function rolls N dimensional die with biasing provided''' # do something return result &gt;&gt; N=6 &gt;&gt; bias=( 0.20,0.20,0.15,0.15,0.14,0.16,) &gt;&gt; roll(N,bias) 2 </code></pre>
3
2009-01-26T09:37:47Z
479,950
<p>See the recipe for <a href="http://code.activestate.com/recipes/576564" rel="nofollow">Walker's alias method</a> for random objects with different probablities.<br /> An example, strings A B C or D with probabilities .1 .2 .3 .4 --</p> <pre><code>abcd = dict( A=1, D=4, C=3, B=2 ) # keys can be any immutables: 2d points, colors, atoms ... wrand = Walkerrandom( abcd.values(), abcd.keys() ) wrand.random() # each call -&gt; "A" "B" "C" or "D" # fast: 1 randint(), 1 uniform(), table lookup </code></pre> <p>cheers<br /> -- denis</p>
1
2009-01-26T14:29:01Z
[ "python", "probability" ]
How do I simulate biased die in python?
479,236
<p>I want to simulate N-sided biased die? </p> <pre><code>def roll(N,bias): '''this function rolls N dimensional die with biasing provided''' # do something return result &gt;&gt; N=6 &gt;&gt; bias=( 0.20,0.20,0.15,0.15,0.14,0.16,) &gt;&gt; roll(N,bias) 2 </code></pre>
3
2009-01-26T09:37:47Z
21,952,241
<p>Just to suggest a more efficient (and pythonic3) solution, one can use <a href="http://docs.python.org/3.3/library/bisect.html#module-bisect" rel="nofollow">bisect</a> to search in the vector of accumulated values — that can moreover be precomputed and stored in the hope that subsequent calls to the function will refer to the same "bias" (to follow the question parlance).</p> <pre><code>from bisect import bisect from itertools import accumulate from random import uniform def pick( amplitudes ): if pick.amplitudes != amplitudes: pick.dist = list( accumulate( amplitudes ) ) pick.amplitudes = amplitudes return bisect( pick.dist, uniform( 0, pick.dist[ -1 ] ) ) pick.amplitudes = None </code></pre> <p>In absence of Python 3 accumulate, one can just write a simple loop to compute the cumulative sum.</p>
0
2014-02-22T09:14:39Z
[ "python", "probability" ]
How do I simulate biased die in python?
479,236
<p>I want to simulate N-sided biased die? </p> <pre><code>def roll(N,bias): '''this function rolls N dimensional die with biasing provided''' # do something return result &gt;&gt; N=6 &gt;&gt; bias=( 0.20,0.20,0.15,0.15,0.14,0.16,) &gt;&gt; roll(N,bias) 2 </code></pre>
3
2009-01-26T09:37:47Z
35,920,548
<pre><code>from random import random biases = [0.0,0.3,0.5,0.99] coins = [1 if random()&lt;bias else 0 for bias in biases] </code></pre>
0
2016-03-10T15:22:48Z
[ "python", "probability" ]
All nodeValue fields are None when parsing XML
479,751
<p>I'm building a simple web-based RSS reader in Python, but I'm having trouble parsing the XML. I started out by trying some stuff in the Python command line.</p> <pre><code>&gt;&gt;&gt; from xml.dom import minidom &gt;&gt;&gt; import urllib2 &gt;&gt;&gt; url ='http://www.digg.com/rss/index.xml' &gt;&gt;&gt; xmldoc = minidom.parse(urllib2.urlopen(url)) &gt;&gt;&gt; channelnode = xmldoc.getElementsByTagName("channel") &gt;&gt;&gt; channelnode = xmldoc.getElementsByTagName("channel") &gt;&gt;&gt; titlenode = channelnode[0].getElementsByTagName("title") &gt;&gt;&gt; print titlenode[0] &lt;DOM Element: title at 0xb37440&gt; &gt;&gt;&gt; print titlenode[0].nodeValue None </code></pre> <p>I played around with this for a while, but the <code>nodeValue</code> of everything seems to be <code>None</code>. Yet if you look at the XML, there definitely are values there. What am I doing wrong?</p>
7
2009-01-26T13:15:03Z
479,766
<p>For RSS feeds you should try the <a href="http://code.google.com/p/feedparser/" rel="nofollow">Universal Feed Parser</a> library. It simplifies the handling of RSS feeds immensly.</p> <pre><code>import feedparser d = feedparser.parse('http://www.digg.com/rss/index.xml') title = d.channel.title </code></pre>
16
2009-01-26T13:21:44Z
[ "python", "xml", "rss", "minidom" ]
All nodeValue fields are None when parsing XML
479,751
<p>I'm building a simple web-based RSS reader in Python, but I'm having trouble parsing the XML. I started out by trying some stuff in the Python command line.</p> <pre><code>&gt;&gt;&gt; from xml.dom import minidom &gt;&gt;&gt; import urllib2 &gt;&gt;&gt; url ='http://www.digg.com/rss/index.xml' &gt;&gt;&gt; xmldoc = minidom.parse(urllib2.urlopen(url)) &gt;&gt;&gt; channelnode = xmldoc.getElementsByTagName("channel") &gt;&gt;&gt; channelnode = xmldoc.getElementsByTagName("channel") &gt;&gt;&gt; titlenode = channelnode[0].getElementsByTagName("title") &gt;&gt;&gt; print titlenode[0] &lt;DOM Element: title at 0xb37440&gt; &gt;&gt;&gt; print titlenode[0].nodeValue None </code></pre> <p>I played around with this for a while, but the <code>nodeValue</code> of everything seems to be <code>None</code>. Yet if you look at the XML, there definitely are values there. What am I doing wrong?</p>
7
2009-01-26T13:15:03Z
479,780
<p>This is the syntax you are looking for:</p> <pre><code>&gt;&gt;&gt; print titlenode[0].firstChild.nodeValue digg.com: Stories / Popular </code></pre> <p>Note that the node value is a logical descendant of the node itself.</p>
10
2009-01-26T13:26:05Z
[ "python", "xml", "rss", "minidom" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
480,227
<p>Here you have some alternatives: <a href="http://www.peterbe.com/plog/uniqifiers-benchmark">http://www.peterbe.com/plog/uniqifiers-benchmark</a></p> <p>Fastest one:</p> <pre><code>def f7(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] </code></pre> <p>Why assign <code>seen.add</code> to <code>seen_add</code> instead of just calling <code>seen.add</code>? Python is a dynamic language, and resolving <code>seen.add</code> each iteration is more costly than resolving a local variable. <code>seen.add</code> could have changed between iterations, and the runtime isn't smart enough to rule that out. To play it safe, it has to check the object each time.</p> <p>If you plan on using this function a lot on the same dataset, perhaps you would be better off with an ordered set: <a href="http://code.activestate.com/recipes/528878/">http://code.activestate.com/recipes/528878/</a></p> <p><em>O</em>(1) insertion, deletion and member-check per operation.</p>
465
2009-01-26T15:47:01Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
480,229
<pre><code>from itertools import groupby [ key for key,_ in groupby(sortedList)] </code></pre> <p>The list doesn't even have to be <em>sorted</em>, the sufficient condition is that equal values are grouped together.</p> <p><strong>Edit: I assumed that "preserving order" implies that the list is actually ordered. If this is not the case, then the solution from MizardX is the right one.</strong></p> <p>Community edit: This is however the most elegant way to "compress duplicate consecutive elements into a single element".</p>
18
2009-01-26T15:47:14Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
1,420,478
<pre><code>for i in range(len(theArray)-1,-1,-1): #get the indexes in reverse if theArray.count(theArray[i]) &gt; 1: theArray.pop(i) </code></pre>
-1
2009-09-14T09:15:08Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
6,959,997
<p>If you need one liner then maybe this would help:</p> <pre><code>reduce(lambda x, y: x + y if y[0] not in x else x, map(lambda x: [x],lst)) </code></pre> <p>... should work but correct me if i'm wrong</p>
1
2011-08-05T17:06:25Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
7,140,776
<p>For no hashable types (e.g. list of lists), based on MizardX's:</p> <pre><code>def f7_noHash(seq) seen = set() return [ x for x in seq if str( x ) not in seen and not seen.add( str( x ) )] </code></pre>
5
2011-08-21T20:04:12Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
7,704,123
<p>MizardX's answer gives a good collection of multiple approaches.</p> <p>This is what I came up with while thinking aloud:</p> <pre><code>mylist = [x for i,x in enumerate(mylist) if x not in mylist[i+1:]] </code></pre>
2
2011-10-09T14:16:00Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
10,485,907
<p>This is fast but...</p> <pre><code>l = list(set(l)) </code></pre> <p>... it doesn't work if your list items aren't hashable.</p> <p>A more generic approach is:</p> <pre><code>l = reduce(lambda x, y: x if y in x else x + [y], l, []) </code></pre> <p>... it should work for all cases.</p>
0
2012-05-07T16:51:33Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
11,280,704
<p>Pop the duplicate in a list and hold uniques in source list :</p> <pre><code>&gt;&gt;&gt; list1 = [ 1,1,2,2,3,3 ] &gt;&gt;&gt; [ list1.pop(i) for i in range(len(list1))[::-1] if list1.count(list1[i]) &gt; 1 ] [1, 2, 3] </code></pre> <p>I use <code>[::-1]</code> for read list in reverse order.</p>
1
2012-07-01T08:52:56Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
13,262,682
<p>You can reference a list comprehension as it is being built by the symbol '_[1]'. <br>For example, the following function unique-ifies a list of elements without changing their order by referencing its list comprehension.</p> <pre><code>def unique(my_list): return [x for x in my_list if x not in locals()['_[1]']] </code></pre> <p>Demo:</p> <pre><code>l1 = [1, 2, 3, 4, 1, 2, 3, 4, 5] l2 = [x for x in l1 if x not in locals()['_[1]']] print l2 </code></pre> <p>Output:</p> <pre><code>[1, 2, 3, 4, 5] </code></pre>
3
2012-11-07T03:21:34Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
15,050,107
<pre><code>&gt;&gt;&gt; myList = [1, 2, 3, 3, 2, 2, 4, 5, 5] &gt;&gt;&gt; myList = list(set(myList)) &gt;&gt;&gt; myList [1, 2, 3, 4, 5] </code></pre>
-3
2013-02-24T08:46:51Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
15,686,617
<p>If your situation allows, you might consider removing duplicates as you load:</p> <p>Say you have a loop that is pulling in data and uses list1.append(item)...</p> <pre><code>list1 = [0, 2, 4, 9] for x in range(0, 7): list1.append(x) </code></pre> <p>That gives you some duplicates: [0, 2, 4, 9, 0, 1, 2, 3, 4, 5, 6]</p> <p>But if you did:</p> <pre><code>list1 = [0, 2, 4, 9] for x in range(0, 7) if x not in list1: list1.append(x) </code></pre> <p>You get no duplicates and the order is preserved: [0, 2, 4, 9, 1, 3, 5, 6]</p>
0
2013-03-28T16:02:15Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
15,990,766
<pre><code>sequence = ['1', '2', '3', '3', '6', '4', '5', '6'] unique = [] [unique.append(item) for item in sequence if item not in unique] </code></pre> <p>unique → <code>['1', '2', '3', '6', '4', '5']</code></p>
28
2013-04-13T17:32:19Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
16,780,848
<p>I think if you wanna maintain the order,</p> <h2>you can try this:</h2> <pre><code>list1 = ['b','c','d','b','c','a','a'] list2 = list(set(list1)) list2.sort(key=list1.index) print list2 </code></pre> <h2>OR similarly you can do this:</h2> <pre><code>list1 = ['b','c','d','b','c','a','a'] list2 = sorted(set(list1),key=list1.index) print list2 </code></pre> <h2>You can also do this:</h2> <pre><code>list1 = ['b','c','d','b','c','a','a'] list2 = [] for i in list1: if not i in list2: list2.append(i)` print list2 </code></pre> <h2>It can also be written as this:</h2> <pre><code>list1 = ['b','c','d','b','c','a','a'] list2 = [] [list2.append(i) for i in list1 if not i in list2] print list2 </code></pre>
14
2013-05-27T21:37:23Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
17,016,257
<p><strong>Important Edit 2015</strong></p> <p>As <a href="http://stackoverflow.com/a/19279812/1219006">@abarnert</a> notes, the <a href="https://pythonhosted.org/more-itertools/api.html"><code>more_itertools</code></a> library (<code>pip install more_itertools</code>) contains a <a href="https://pythonhosted.org/more-itertools/api.html#more_itertools.unique_everseen"><code>unique_everseen</code></a> function that is built to solve this problem without any <strong>unreadable</strong> (<code>not seen.add</code>) <strong>mutations</strong> in list comprehensions. This is also the fastest solution too:</p> <pre><code>&gt;&gt;&gt; from more_itertools import unique_everseen &gt;&gt;&gt; items = [1, 2, 0, 1, 3, 2] &gt;&gt;&gt; list(unique_everseen(items)) [1, 2, 0, 3] </code></pre> <p>Just one simple library import and no hacks. This comes from an implementation of the itertools recipe <a href="https://docs.python.org/3/library/itertools.html#itertools-recipes"><code>unique_everseen</code></a> which looks like:</p> <pre><code>def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --&gt; A B C D # unique_everseen('ABBCcAD', str.lower) --&gt; A B C D seen = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element </code></pre> <hr> <p>In Python <code>2.7+</code> the <strike>accepted common idiom</strike> (this works but isn't optimized for speed, i would now use <a href="https://pythonhosted.org/more-itertools/api.html#more_itertools.unique_everseen"><code>unique_everseen</code></a>) for this uses <a href="http://docs.python.org/3/library/collections.html#collections.OrderedDict"><code>collections.OrderedDict</code></a>:</p> <p>Runtime: <strong>O(N)</strong></p> <pre><code>&gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; items = [1, 2, 0, 1, 3, 2] &gt;&gt;&gt; list(OrderedDict.fromkeys(items)) [1, 2, 0, 3] </code></pre> <p>This looks much nicer than:</p> <pre><code>seen = set() [x for x in seq if x not in seen and not seen.add(x)] </code></pre> <p>and doesn't utilize the <strong>ugly hack</strong>:</p> <pre><code>not seen.add(x) </code></pre> <p>which relies on the fact that <code>set.add</code> is an in-place method that always returns <code>None</code> so <code>not None</code> evaluates to <code>True</code>. </p> <p>Note however that the hack solution is faster in raw speed though it has the same runtime complexity O(N).</p>
224
2013-06-10T02:47:13Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
18,729,193
<p>Borrowing the recursive idea used in definining Haskell's <code>nub</code> function for lists, this would be a recursive approach:</p> <pre><code>def unique(lst): return [] if lst==[] else [lst[0]] + unique(filter(lambda x: x!= lst[0], lst[1:])) </code></pre> <p>e.g.:</p> <pre><code>In [118]: unique([1,5,1,1,4,3,4]) Out[118]: [1, 5, 4, 3] </code></pre> <p>I tried it for growing data sizes and saw sub-linear time-complexity (not definitive, but suggests this should be fine for normal data).</p> <pre><code>In [122]: %timeit unique(np.random.randint(5, size=(1))) 10000 loops, best of 3: 25.3 us per loop In [123]: %timeit unique(np.random.randint(5, size=(10))) 10000 loops, best of 3: 42.9 us per loop In [124]: %timeit unique(np.random.randint(5, size=(100))) 10000 loops, best of 3: 132 us per loop In [125]: %timeit unique(np.random.randint(5, size=(1000))) 1000 loops, best of 3: 1.05 ms per loop In [126]: %timeit unique(np.random.randint(5, size=(10000))) 100 loops, best of 3: 11 ms per loop </code></pre> <p>I also think it's interesting that this could be readily generalized to uniqueness by other operations. Like this:</p> <pre><code>import operator def unique(lst, cmp_op=operator.ne): return [] if lst==[] else [lst[0]] + unique(filter(lambda x: cmp_op(x, lst[0]), lst[1:]), cmp_op) </code></pre> <p>For example, you could pass in a function that uses the notion of rounding to the same integer as if it was "equality" for uniqueness purposes, like this:</p> <pre><code>def test_round(x,y): return round(x) != round(y) </code></pre> <p>then unique(some_list, test_round) would provide the unique elements of the list where uniqueness no longer meant traditional equality (which is implied by using any sort of set-based or dict-key-based approach to this problem) but instead meant to take only the first element that rounds to K for each possible integer K that the elements might round to, e.g.:</p> <pre><code>In [6]: unique([1.2, 5, 1.9, 1.1, 4.2, 3, 4.8], test_round) Out[6]: [1.2, 5, 1.9, 4.2, 3] </code></pre>
2
2013-09-10T21:40:58Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
19,135,774
<p>Relatively effective approach with <code>_sorted_</code> a <code>numpy</code> arrays:</p> <pre><code>b = np.array([1,3,3, 8, 12, 12,12]) numpy.hstack([b[0], [x[0] for x in zip(b[1:], b[:-1]) if x[0]!=x[1]]]) </code></pre> <p>Outputs:</p> <pre><code>array([ 1, 3, 8, 12]) </code></pre>
1
2013-10-02T11:23:31Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
19,279,812
<p>For another very late answer to another very old question:</p> <p>The <a href="http://docs.python.org/3/library/itertools.html#itertools-recipes"><code>itertools</code> recipes</a> have a function that does this, using the <code>seen</code> set technique, but:</p> <ul> <li>Handles a standard <code>key</code> function.</li> <li>Uses no unseemly hacks.</li> <li>Optimizes the loop by pre-binding <code>seen.add</code> instead of looking it up N times. (<code>f7</code> also does this, but some versions don't.)</li> <li>Optimizes the loop by using <code>ifilterfalse</code>, so you only have to loop over the unique elements in Python, instead of all of them. (You still iterate over all of them inside <code>ifilterfalse</code>, of course, but that's in C, and much faster.)</li> </ul> <p>Is it actually faster than <code>f7</code>? It depends on your data, so you'll have to test it and see. If you want a list in the end, <code>f7</code> uses a listcomp, and there's no way to do that here. (You can directly <code>append</code> instead of <code>yield</code>ing, or you can feed the generator into the <code>list</code> function, but neither one can be as fast as the LIST_APPEND inside a listcomp.) At any rate, usually, squeezing out a few microseconds is not going to be as important as having an easily-understandable, reusable, already-written function that doesn't require DSU when you want to decorate.</p> <p>As with all of the recipes, it's also available in <a href="https://pypi.python.org/pypi/more-itertools"><code>more-iterools</code></a>.</p> <p>If you just want the no-<code>key</code> case, you can simplify it as:</p> <pre><code>def unique(iterable): seen = set() seen_add = seen.add for element in itertools.ifilterfalse(seen.__contains__, iterable): seen_add(element) yield element </code></pre>
7
2013-10-09T18:27:09Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
21,119,677
<p>Because I was looking at a <a href="http://stackoverflow.com/q/4459703/1174169">dup</a> and collected some related but different, related, useful information that isn't part of the other answers, here are two other possible solutions. </p> <p><strong>.get(True) XOR .setdefault(False)</strong></p> <p>The first is very much like the accepted <code>seen_add</code> soultion but with explicit side effects using dictionary's <code>get(x,&lt;default&gt;)</code> and <code>setdefault(x,&lt;default&gt;)</code>:</p> <pre><code># Explanation of d.get(x,True) != d.setdefault(x,False) # # x in d | d[x] | A = d.get(x,True) | x in d | B = d.setdefault(x,False) | x in d | d[x] | A xor B # False | None | True (1) | False | False (2) | True | False | True # True | False | False (3) | True | False (4) | True | False | False # # Notes # (1) x is not in the dictionary, so get(x,&lt;default&gt;) returns True but does __not__ add the value to the dictionary # (2) x is not in the dictionary, so setdefault(x,&lt;default&gt;) adds the {x:False} and returns False # (3) since x is in the dictionary, the &lt;default&gt; argument is ignored, and the value of the key is returned, which was # set to False in (2) # (4) since the key is already in the dictionary, its value is returned directly and the argument is ignored # # A != B is how to do boolean XOR in Python # def sort_with_order(s): d = dict() return [x for x in s if d.get(x,True) != d.setdefault(x,False)] </code></pre> <p><code>get(x,&lt;default&gt;)</code> returns <code>&lt;default&gt;</code> if <code>x</code> is not in the dictionary, but does not add the key to the dictionary. <code>set(x,&lt;default&gt;)</code> returns the value if the key is in the dictionary, otherwise sets it to and returns <code>&lt;default&gt;</code>.</p> <p>Aside: <a href="http://stackoverflow.com/a/433161/1174169"><code>a != b</code> is how to do an XOR in python</a></p> <p><strong>OVERRIDING __<em>missing</em>__</strong> (inspired by <a href="http://stackoverflow.com/a/14507623/1174169">this answer</a>)</p> <p>The second technique is overriding the <code>__missing__</code> method that gets called when the key doesn't exist in a dictionary, which is only called when using <code>d[k]</code> notation:</p> <pre><code>class Tracker(dict): # returns True if missing, otherwise sets the value to False # so next time d[key] is called, the value False will be returned # and __missing__ will not be called again def __missing__(self, key): self[key] = False return True t = Tracker() unique_with_order = [x for x in samples if t[x]] </code></pre> <p>From <a href="http://docs.python.org/2/library/stdtypes.html#mapping-types-dict" rel="nofollow">the docs</a>:</p> <blockquote> <p>New in version 2.5: If a subclass of dict defines a method <strong>__<em>missing</em>__</strong>(), if the key key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the <strong>__<em>missing</em>__</strong>(key) call if the key is not present. No other operations or methods invoke <strong>__<em>missing</em>__</strong>(). If <strong>__<em>missing</em>__</strong>() is not defined, KeyError is raised. <strong>__<em>missing</em>__</strong>() must be a method; it cannot be an instance variable. For an example, see collections.defaultdict.</p> </blockquote>
1
2014-01-14T17:14:50Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
23,282,700
<p>You could do a sort of ugly list comprehension hack.</p> <pre><code>[l[i] for i in range(len(l)) if l.index(l[i]) == i] </code></pre>
1
2014-04-25T01:28:31Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
23,919,756
<pre><code>l = [1,2,3,4,5,1,2,3,4] s = set(l) l = list(s) print l </code></pre> <p><strong>Output:</strong></p> <pre><code>[1,2,3,4,5] </code></pre>
0
2014-05-28T18:59:25Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
24,914,302
<pre><code>inpList = [1, 1, 2, 2, 3, 3, 2, 2, 4, 1, 2, 5, 5] myList = list(set(inpList)) print myList </code></pre> <blockquote> <p>output: [1, 2, 3, 4, 5]</p> </blockquote>
1
2014-07-23T15:12:18Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
26,794,407
<pre><code>l = [1,2,2,3,3,...] n = [] n.extend(ele for ele in l if ele not in set(n)) </code></pre> <p>A generator expression that uses the O(1) look up of a set to determine whether or not to include an element in the new list.</p>
1
2014-11-07T05:02:54Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
27,466,786
<p>Here is an O(N<sup>2</sup>) recursive version for fun:</p> <pre><code>def uniquify(s): if len(s) &lt; 2: return s return uniquify(s[:-1]) + [s[-1]] * (s[-1] not in s[:-1]) </code></pre>
1
2014-12-14T06:01:13Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
29,898,968
<p>5 x faster reduce variant but more sophisticated</p> <pre><code>&gt;&gt;&gt; l = [5, 6, 6, 1, 1, 2, 2, 3, 4] &gt;&gt;&gt; reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0] [5, 6, 1, 2, 3, 4] </code></pre> <p>Explanation:</p> <pre><code>default = (list(), set()) # use list to keep order # use set to make lookup faster def reducer(result, item): if item not in result[1]: result[0].append(item) result[1].add(item) return result &gt;&gt;&gt; reduce(reducer, l, default)[0] [5, 6, 1, 2, 3, 4] </code></pre>
3
2015-04-27T14:47:21Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
30,281,633
<p>A simple recursive solution:</p> <pre><code>def uniquefy_list(a): return uniquefy_list(a[1:]) if a[0] in a[1:] else [a[0]]+uniquefy_list(a[1:]) if len(a)&gt;1 else [a[0]] </code></pre>
1
2015-05-16T23:05:08Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
31,486,477
<p>If you routinely use <a href="http://pandas.pydata.org/" rel="nofollow"><code>pandas</code></a>, and aesthetics is preferred over performance, then consider the built-in function <code>pandas.Series.drop_duplicates</code>:</p> <pre><code> import pandas as pd import numpy as np uniquifier = lambda alist: pd.Series(alist).drop_duplicates().tolist() # from the chosen answer def f7(seq): seen = set() seen_add = seen.add return [ x for x in seq if not (x in seen or seen_add(x))] alist = np.random.randint(low=0, high=1000, size=10000).tolist() print uniquifier(alist) == f7(alist) # True </code></pre> <p>Timing: </p> <pre><code> In [104]: %timeit f7(alist) 1000 loops, best of 3: 1.3 ms per loop In [110]: %timeit uniquifier(alist) 100 loops, best of 3: 4.39 ms per loop </code></pre>
0
2015-07-18T00:10:51Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
32,291,752
<p>Here is my 2 cents on this:</p> <pre><code>def unique(nums): unique = [] for n in nums: if n not in unique: unique.append(n) return unique </code></pre> <p>Regards, Yuriy</p>
-1
2015-08-29T23:40:36Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
33,031,508
<pre><code>list1 = [1,2,3,4,5,7,8,9,4,1,2,35,1,2,4,2,3] #convert list into set set = set(list1) #convert back to list list1 = list(set) print list1 #Ans: [1,2,3,4,5,7,8,9,4,1,2,35,1,2,] </code></pre>
-2
2015-10-09T06:39:49Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
33,393,971
<p>I found a very elegant and ultra fast way to do this here: <a href="http://www.peterbe.com/plog/uniqifiers-benchmark" rel="nofollow">http://www.peterbe.com/plog/uniqifiers-benchmark</a></p> <pre><code>def f1(seq): # not order preserving set = {} map(set.__setitem__, seq, []) return set.keys() </code></pre>
-2
2015-10-28T14:36:29Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
34,749,886
<p>this will preserve order and run in O(n) time. basically the idea is to create a hole wherever there is a duplicate found and sink it down to the bottom. makes use of a read and write pointer. whenever a duplicate is found only the read pointer advances and write pointer stays on the duplicate entry to overwrite it.</p> <pre><code>def deduplicate(l): count = {} (read,write) = (0,0) while read &lt; len(l): if l[read] in count: read += 1 continue count[l[read]] = True l[write] = l[read] read += 1 write += 1 return l[0:write] </code></pre>
0
2016-01-12T17:16:19Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
35,038,274
<p>A solution without using imported modules or sets:</p> <pre><code>text = "ask not what your country can do for you ask what you can do for your country" sentence = text.split(" ") noduplicates = [(sentence[i]) for i in range (0,len(sentence)) if sentence[i] not in sentence[:i]] print(noduplicates) </code></pre> <p>Gives output:</p> <pre><code>['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you'] </code></pre>
0
2016-01-27T13:08:08Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
39,456,312
<p>this is the smartes way to remove duplicates from a list in Python whilst preserving its order, you can even do it in one line of code:</p> <pre><code>a_list = ["a", "b", "a", "c"] sorted_list = [x[0] for x in (sorted({x:a_list.index(x) for x in set(a_list)}.items(), key=lambda x: x[1]))] print sorted_list </code></pre>
0
2016-09-12T18:13:13Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
39,564,397
<p>My buddy Wes gave me this sweet answer using list comprehensions.</p> <p>Example Code:</p> <pre><code>&gt;&gt;&gt; l = [3, 4, 3, 6, 4, 1, 4, 8] &gt;&gt;&gt; l = [l[i] for i in range(len(l)) if i == l.index(l[i])] &gt;&gt;&gt; l = [3, 4, 6, 1, 8] </code></pre>
0
2016-09-19T02:03:15Z
[ "python", "list", "duplicates", "unique" ]
How do you remove duplicates from a list in whilst preserving order?
480,214
<p>Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:</p> <pre><code>def uniq(input): output = [] for x in input: if x not in output: output.append(x) return output </code></pre> <p>(Thanks to <a href="http://stackoverflow.com/users/28169/unwind">unwind</a> for that <a href="http://stackoverflow.com/questions/479897/how-do-you-remove-duplicates-from-a-list-in-python#479921">code sample</a>.)</p> <p>But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.</p> <p>Related question: <a href="http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p>
414
2009-01-26T15:43:58Z
39,835,527
<p>As of Python 2.7, the new way for removing duplicates from an iterable while keeping it in the original order is:</p> <pre><code>&gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; list(OrderedDict.fromkeys('abracadabra')) ['a', 'b', 'r', 'c', 'd'] </code></pre> <p>And as of Python 3.5 when <a href="https://docs.python.org/3/library/collections.html#ordereddict-objects" rel="nofollow">OrderedDict</a> was reimplemented in C, this is now the fastest approach as well as the shortest and cleanest.</p>
3
2016-10-03T15:47:33Z
[ "python", "list", "duplicates", "unique" ]
Get the title of the current active Window/Document in Mac OS X
480,866
<p>Refering to a previously asked <a href="http://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python" rel="nofollow" title="question">question</a>, I would like to know how to get the title of the current active document.</p> <p>I tried the script mention in the answers to the question above. This works, but only gives me the name of the application. For example, I am writing this question: When I fire up the script it gives me the name of the application, i.e. "Firefox". This is pretty neat, but does not really help. I would rather like to capture the title of my current active document. See the image. </p> <p><img src="http://img.skitch.com/20090126-nq2egknhjr928d1s74i9xixckf.jpg" alt="Firefox title" /></p> <p>I am using Leopard, so no backward compatibility needed. Also I am using Python's Appkit to gain access to the NSWorkspace class, but if you tell me the Objective-C code, I could figure out the translation to Python. <hr> Ok, I've got a solution which is not very satisfing, thats why I don't mark Koen Bok's answer. At least not yet.</p> <pre><code>tell application "System Events" set frontApp to name of first application process whose frontmost is true end tell tell application frontApp if the (count of windows) is not 0 then set window_name to name of front window end if end tell </code></pre> <p>Save as script and invoke it with osascript from the shell.</p>
13
2009-01-26T18:32:52Z
481,047
<p>As far as I know your best bet is wrapping an AppleScript. But AppleScript is magic to me so I leave it as an exercise for the questioner :-) </p> <p>This might help a little: <a href="http://www.macosxhints.com/article.php?story=20060105082728937&amp;lsrc=osxh">http://www.macosxhints.com/article.php?story=20060105082728937&amp;lsrc=osxh</a></p>
6
2009-01-26T19:38:41Z
[ "python", "objective-c", "osx" ]
Get the title of the current active Window/Document in Mac OS X
480,866
<p>Refering to a previously asked <a href="http://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python" rel="nofollow" title="question">question</a>, I would like to know how to get the title of the current active document.</p> <p>I tried the script mention in the answers to the question above. This works, but only gives me the name of the application. For example, I am writing this question: When I fire up the script it gives me the name of the application, i.e. "Firefox". This is pretty neat, but does not really help. I would rather like to capture the title of my current active document. See the image. </p> <p><img src="http://img.skitch.com/20090126-nq2egknhjr928d1s74i9xixckf.jpg" alt="Firefox title" /></p> <p>I am using Leopard, so no backward compatibility needed. Also I am using Python's Appkit to gain access to the NSWorkspace class, but if you tell me the Objective-C code, I could figure out the translation to Python. <hr> Ok, I've got a solution which is not very satisfing, thats why I don't mark Koen Bok's answer. At least not yet.</p> <pre><code>tell application "System Events" set frontApp to name of first application process whose frontmost is true end tell tell application frontApp if the (count of windows) is not 0 then set window_name to name of front window end if end tell </code></pre> <p>Save as script and invoke it with osascript from the shell.</p>
13
2009-01-26T18:32:52Z
23,451,568
<p>In Objective-C, the short answer, using a little Cocoa and mostly the <a href="https://developer.apple.com/library/mac/documentation/Accessibility/Reference/AccessibilityCarbonRef/Reference/reference.html" rel="nofollow">Carbon Accessibility API</a> is:</p> <pre class="lang-m prettyprint-override"><code>// Get the process ID of the frontmost application. NSRunningApplication* app = [[NSWorkspace sharedWorkspace] frontmostApplication]; pid_t pid = [app processIdentifier]; // See if we have accessibility permissions, and if not, prompt the user to // visit System Preferences. NSDictionary *options = @{(id)kAXTrustedCheckOptionPrompt: @YES}; Boolean appHasPermission = AXIsProcessTrustedWithOptions( (__bridge CFDictionaryRef)options); if (!appHasPermission) { return; // we don't have accessibility permissions // Get the accessibility element corresponding to the frontmost application. AXUIElementRef appElem = AXUIElementCreateApplication(pid); if (!appElem) { return; } // Get the accessibility element corresponding to the frontmost window // of the frontmost application. AXUIElementRef window = NULL; if (AXUIElementCopyAttributeValue(appElem, kAXFocusedWindowAttribute, (CFTypeRef*)&amp;window) != kAXErrorSuccess) { CFRelease(appElem); return; } // Finally, get the title of the frontmost window. CFStringRef title = NULL; AXError result = AXUIElementCopyAttributeValue(window, kAXTitleAttribute, (CFTypeRef*)&amp;title); // At this point, we don't need window and appElem anymore. CFRelease(window); CFRelease(appElem); if (result != kAXErrorSuccess) { // Failed to get the window title. return; } // Success! Now, do something with the title, e.g. copy it somewhere. // Once we're done with the title, release it. CFRelease(title); </code></pre> <p>Alternatively, it may be simpler to use the CGWindow API, as alluded to in <a href="http://stackoverflow.com/a/3042284/308464">this StackOverflow answer</a>.</p>
2
2014-05-04T01:20:22Z
[ "python", "objective-c", "osx" ]
Is there a way in python to apply a list of regex patterns that are stored in a list to a single string?
481,266
<p>i have a list of regex patterns (stored in a list type) that I would like to apply to a string.</p> <p>Does anyone know a good way to:</p> <ol> <li>Apply every regex pattern in the list to the string and</li> <li>Call a different function that is associated with that pattern in the list if it matches.</li> </ol> <p>I would like to do this in python if possible</p> <p>thanks in advance.</p>
3
2009-01-26T20:43:24Z
481,280
<pre><code>import re def func1(s): print s, "is a nice string" def func2(s): print s, "is a bad string" funcs = { r".*pat1.*": func1, r".*pat2.*": func2 } s = "Some string with both pat1 and pat2" for pat, func in funcs.items(): if re.search(pat, s): func(s) </code></pre> <p>The above code will call both functions for the string <code>s</code> because both patterns are matched.</p>
9
2009-01-26T20:49:24Z
[ "python", "regex", "list" ]
Can a lambda function call itself recursively in Python?
481,692
<p>A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?</p>
49
2009-01-26T22:42:42Z
481,740
<p>I have never used Python, but <a href="http://siddhi.blogspot.com/2007/08/y-combinator-in-python.html">this</a> is probably what you are looking for.</p>
6
2009-01-26T22:59:32Z
[ "python", "recursion", "lambda", "y-combinator" ]
Can a lambda function call itself recursively in Python?
481,692
<p>A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?</p>
49
2009-01-26T22:42:42Z
481,755
<p>The only way I can think of to do this amounts to giving the function a name:</p> <pre><code>fact = lambda x: 1 if x == 0 else x * fact(x-1) </code></pre> <p>or alternately, for earlier versions of python:</p> <pre><code>fact = lambda x: x == 0 and 1 or x * fact(x-1) </code></pre> <p><strong>Update</strong>: using the ideas from the other answers, I was able to wedge the factorial function into a single unnamed lambda:</p> <pre><code>&gt;&gt;&gt; map(lambda n: (lambda f, *a: f(f, *a))(lambda rec, n: 1 if n == 0 else n*rec(rec, n-1), n), range(10)) [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] </code></pre> <p>So it's possible, but not really recommended!</p>
48
2009-01-26T23:04:03Z
[ "python", "recursion", "lambda", "y-combinator" ]
Can a lambda function call itself recursively in Python?
481,692
<p>A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?</p>
49
2009-01-26T22:42:42Z
481,790
<p>You can't directly do it, because it has no name. But with a helper function like the Y-combinator Lemmy pointed to, you can create recursion by passing the function as a parameter to itself (as strange as that sounds):</p> <pre><code># helper function def recursive(f, *p, **kw): return f(f, *p, **kw) def fib(n): # The rec parameter will be the lambda function itself return recursive((lambda rec, n: rec(rec, n-1) + rec(rec, n-2) if n&gt;1 else 1), n) # using map since we already started to do black functional programming magic print map(fib, range(10)) </code></pre> <p>This prints the first ten Fibonacci numbers: <code>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]</code>, </p>
21
2009-01-26T23:16:29Z
[ "python", "recursion", "lambda", "y-combinator" ]
Can a lambda function call itself recursively in Python?
481,692
<p>A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?</p>
49
2009-01-26T22:42:42Z
481,793
<p>If you were truly masochistic, you might be able to do it using C extensions, but to echo Greg (hi Greg!), this exceeds the capability of a lambda (unnamed, anonymous) functon.</p> <p>No. (for most values of no).</p>
0
2009-01-26T23:17:39Z
[ "python", "recursion", "lambda", "y-combinator" ]
Can a lambda function call itself recursively in Python?
481,692
<p>A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?</p>
49
2009-01-26T22:42:42Z
482,200
<p>Yes. I have two ways to do it, and one was already covered. This is my preferred way.</p> <pre><code>(lambda v: (lambda n: n * __import__('types').FunctionType( __import__('inspect').stack()[0][0].f_code, dict(__import__=__import__, dict=dict) )(n - 1) if n &gt; 1 else 1)(v))(5) </code></pre>
9
2009-01-27T02:52:33Z
[ "python", "recursion", "lambda", "y-combinator" ]
Can a lambda function call itself recursively in Python?
481,692
<p>A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?</p>
49
2009-01-26T22:42:42Z
8,703,135
<p>without reduce, map, named lambdas or python internals:</p> <pre><code>(lambda a:lambda v:a(a,v))(lambda s,x:1 if x==0 else x*s(s,x-1))(10) </code></pre>
35
2012-01-02T16:34:15Z
[ "python", "recursion", "lambda", "y-combinator" ]
Can a lambda function call itself recursively in Python?
481,692
<p>A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?</p>
49
2009-01-26T22:42:42Z
10,144,992
<p>Contrary to what sth said, you CAN directly do this.</p> <pre><code>(lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))(lambda f: (lambda i: 1 if (i == 0) else i * f(i - 1)))(n) </code></pre> <p>The first part is the <a href="http://en.wikipedia.org/wiki/Fixed-point_combinator#Example_in_Python">fixed-point combinator</a> <em>Y</em> that facilitates recursion in lambda calculus</p> <pre><code>Y = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v)))) </code></pre> <p>the second part is the factorial function <em>fact</em> defined recursively</p> <pre><code>fact = (lambda f: (lambda i: 1 if (i == 0) else i * f(i - 1))) </code></pre> <p><em>Y</em> is applied to <em>fact</em> to form another lambda expression</p> <pre><code>F = Y(fact) </code></pre> <p>which is applied to the third part, <em>n</em>, which evaulates to the nth factorial</p> <pre><code>&gt;&gt;&gt; n = 5 &gt;&gt;&gt; F(n) 120 </code></pre> <p>or equivalently</p> <pre><code>&gt;&gt;&gt; (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))(lambda f: (lambda i: 1 if (i == 0) else i * f(i - 1)))(5) 120 </code></pre> <p>If however you prefer <em>fibs</em> to <em>facts</em> you can do that too using the same combinator</p> <pre><code>&gt;&gt;&gt; (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))(lambda f: (lambda i: f(i - 1) + f(i - 2) if i &gt; 1 else 1))(5) 8 </code></pre>
16
2012-04-13T16:50:05Z
[ "python", "recursion", "lambda", "y-combinator" ]
Can a lambda function call itself recursively in Python?
481,692
<p>A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?</p>
49
2009-01-26T22:42:42Z
25,379,621
<p>Well, not exactly pure lambda recursion, but it's applicable in places, where you can only use lambdas, e.g. reduce, map and list comprehensions, or other lambdas. The trick is to benefit from list comprehension and Python's name scope. The following example traverses the dictionary by the given chain of keys.</p> <pre><code>&gt;&gt;&gt; data = {'John': {'age': 33}, 'Kate': {'age': 32}} &gt;&gt;&gt; [fn(data, ['John', 'age']) for fn in [lambda d, keys: None if d is None or type(d) is not dict or len(keys) &lt; 1 or keys[0] not in d else (d[keys[0]] if len(keys) == 1 else fn(d[keys[0]], keys[1:]))]][0] 33 </code></pre> <p>The lambda reuses its name defined in the list comprehension expression (fn). The example is rather complicated, but it shows the concept.</p>
0
2014-08-19T09:11:22Z
[ "python", "recursion", "lambda", "y-combinator" ]
Can a lambda function call itself recursively in Python?
481,692
<p>A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How?</p>
49
2009-01-26T22:42:42Z
36,252,530
<p>This answer is pretty basic. It is a little simpler than Hugo Walter's answer:</p> <pre><code>&gt;&gt;&gt; (lambda f: f(f))(lambda f, i=0: (i &lt; 10)and f(f, i + 1)or i) 10 &gt;&gt;&gt; </code></pre> <p>Hugo Walter's answer:</p> <pre><code>(lambda a:lambda v:a(a,v))(lambda s,x:1 if x==0 else x*s(s,x-1))(10) </code></pre>
1
2016-03-27T20:53:14Z
[ "python", "recursion", "lambda", "y-combinator" ]
Extracting info from large structured text files
481,862
<p>I need to read some large files (from 50k to 100k lines), structured in groups separated by empty lines. Each group start at the same pattern "No.999999999 dd/mm/yyyy ZZZ". Here´s some sample data.</p> <blockquote> <p>No.813829461 16/09/1987 270<br /> Tit.SUZANO PAPEL E CELULOSE S.A. (BR/BA)<br /> C.N.P.J./C.I.C./N INPI : 16404287000155<br /> Procurador: MARCELLO DO NASCIMENTO </p> <p>No.815326777 28/12/1989 351<br /> Tit.SIGLA SISTEMA GLOBO DE GRAVACOES AUDIO VISUAIS LTDA (BR/RJ)<br /> C.N.P.J./C.I.C./NºINPI : 34162651000108<br /> Apres.: Nominativa ; Nat.: De Produto<br /> Marca: TRIO TROPICAL<br /> Clas.Prod/Serv: 09.40<br /> *DEFERIDO CONFORME RESOLUÇÃO 123 DE 06/01/2006, PUBLICADA NA RPI 1829, DE 24/01/2006.<br /> Procurador: WALDEMAR RODRIGUES PEDRA </p> <p>No.900148764 11/01/2007 LD3<br /> Tit.TIARA BOLSAS E CALÇADOS LTDA<br /> Procurador: Marcia Ferreira Gomes<br /> *Escritório: Marcas Marcantes e Patentes Ltda<br /> *Exigência Formal não respondida Satisfatoriamente, Pedido de Registro de Marca considerado inexistente, de acordo com Art. 157 da LPI<br /> *Protocolo da Petição de cumprimento de Exigência Formal: 810080140197</p> </blockquote> <p>I wrote some code that´s parsing it accordingly. There´s anything that I can improve, to improve readability or performance? Here´s what I come so far:</p> <pre><code>import re, pprint class Despacho(object): """ Class to parse each line, applying the regexp and storing the results for future use """ regexp = { re.compile(r'No.([\d]{9}) ([\d]{2}/[\d]{2}/[\d]{4}) (.*)'): lambda self: self._processo, re.compile(r'Tit.(.*)'): lambda self: self._titular, re.compile(r'Procurador: (.*)'): lambda self: self._procurador, re.compile(r'C.N.P.J./C.I.C./N INPI :(.*)'): lambda self: self._documento, re.compile(r'Apres.: (.*) ; Nat.: (.*)'): lambda self: self._apresentacao, re.compile(r'Marca: (.*)'): lambda self: self._marca, re.compile(r'Clas.Prod/Serv: (.*)'): lambda self: self._classe, re.compile(r'\*(.*)'): lambda self: self._complemento, } def __init__(self): """ 'complemento' is the only field that can be multiple in a single registry """ self.complemento = [] def _processo(self, matches): self.processo, self.data, self.despacho = matches.groups() def _titular(self, matches): self.titular = matches.group(1) def _procurador(self, matches): self.procurador = matches.group(1) def _documento(self, matches): self.documento = matches.group(1) def _apresentacao(self, matches): self.apresentacao, self.natureza = matches.groups() def _marca(self, matches): self.marca = matches.group(1) def _classe(self, matches): self.classe = matches.group(1) def _complemento(self, matches): self.complemento.append(matches.group(1)) def read(self, line): for pattern in Despacho.regexp: m = pattern.match(line) if m: Despacho.regexp[pattern](self)(m) def process(rpi): """ read data and process each group """ rpi = (line for line in rpi) group = False for line in rpi: if line.startswith('No.'): group = True d = Despacho() if not line.strip() and group: # empty line - end of block yield d group = False d.read(line) arquivo = open('rm1972.txt') # file to process for desp in process(arquivo): pprint.pprint(desp.__dict__) print('--------------') </code></pre> <p>Thank you.</p> <p>By the way, sorry for my poor english. :)</p>
1
2009-01-26T23:47:04Z
481,890
<p>It would be easier to help if you had a specific concern. Performance will depend greatly on the efficiency of the particular regex engine you are using. 100K lines in a single file doesn't sound that big, but again it all depends on your environment.</p> <p>I use <a href="http://www.ultrapico.com/Expresso.htm" rel="nofollow">Expresso</a> in my .NET development to test expressions for accuracy and performance. A Google search turned up <a href="http://kodos.sourceforge.net/about.html" rel="nofollow">Kodos</a>, a GUI Python regex authoring tool.</p>
1
2009-01-27T00:04:04Z
[ "python", "text-processing" ]
Extracting info from large structured text files
481,862
<p>I need to read some large files (from 50k to 100k lines), structured in groups separated by empty lines. Each group start at the same pattern "No.999999999 dd/mm/yyyy ZZZ". Here´s some sample data.</p> <blockquote> <p>No.813829461 16/09/1987 270<br /> Tit.SUZANO PAPEL E CELULOSE S.A. (BR/BA)<br /> C.N.P.J./C.I.C./N INPI : 16404287000155<br /> Procurador: MARCELLO DO NASCIMENTO </p> <p>No.815326777 28/12/1989 351<br /> Tit.SIGLA SISTEMA GLOBO DE GRAVACOES AUDIO VISUAIS LTDA (BR/RJ)<br /> C.N.P.J./C.I.C./NºINPI : 34162651000108<br /> Apres.: Nominativa ; Nat.: De Produto<br /> Marca: TRIO TROPICAL<br /> Clas.Prod/Serv: 09.40<br /> *DEFERIDO CONFORME RESOLUÇÃO 123 DE 06/01/2006, PUBLICADA NA RPI 1829, DE 24/01/2006.<br /> Procurador: WALDEMAR RODRIGUES PEDRA </p> <p>No.900148764 11/01/2007 LD3<br /> Tit.TIARA BOLSAS E CALÇADOS LTDA<br /> Procurador: Marcia Ferreira Gomes<br /> *Escritório: Marcas Marcantes e Patentes Ltda<br /> *Exigência Formal não respondida Satisfatoriamente, Pedido de Registro de Marca considerado inexistente, de acordo com Art. 157 da LPI<br /> *Protocolo da Petição de cumprimento de Exigência Formal: 810080140197</p> </blockquote> <p>I wrote some code that´s parsing it accordingly. There´s anything that I can improve, to improve readability or performance? Here´s what I come so far:</p> <pre><code>import re, pprint class Despacho(object): """ Class to parse each line, applying the regexp and storing the results for future use """ regexp = { re.compile(r'No.([\d]{9}) ([\d]{2}/[\d]{2}/[\d]{4}) (.*)'): lambda self: self._processo, re.compile(r'Tit.(.*)'): lambda self: self._titular, re.compile(r'Procurador: (.*)'): lambda self: self._procurador, re.compile(r'C.N.P.J./C.I.C./N INPI :(.*)'): lambda self: self._documento, re.compile(r'Apres.: (.*) ; Nat.: (.*)'): lambda self: self._apresentacao, re.compile(r'Marca: (.*)'): lambda self: self._marca, re.compile(r'Clas.Prod/Serv: (.*)'): lambda self: self._classe, re.compile(r'\*(.*)'): lambda self: self._complemento, } def __init__(self): """ 'complemento' is the only field that can be multiple in a single registry """ self.complemento = [] def _processo(self, matches): self.processo, self.data, self.despacho = matches.groups() def _titular(self, matches): self.titular = matches.group(1) def _procurador(self, matches): self.procurador = matches.group(1) def _documento(self, matches): self.documento = matches.group(1) def _apresentacao(self, matches): self.apresentacao, self.natureza = matches.groups() def _marca(self, matches): self.marca = matches.group(1) def _classe(self, matches): self.classe = matches.group(1) def _complemento(self, matches): self.complemento.append(matches.group(1)) def read(self, line): for pattern in Despacho.regexp: m = pattern.match(line) if m: Despacho.regexp[pattern](self)(m) def process(rpi): """ read data and process each group """ rpi = (line for line in rpi) group = False for line in rpi: if line.startswith('No.'): group = True d = Despacho() if not line.strip() and group: # empty line - end of block yield d group = False d.read(line) arquivo = open('rm1972.txt') # file to process for desp in process(arquivo): pprint.pprint(desp.__dict__) print('--------------') </code></pre> <p>Thank you.</p> <p>By the way, sorry for my poor english. :)</p>
1
2009-01-26T23:47:04Z
481,957
<p>It looks good overall, but why do you have the line:</p> <pre><code>rpi = (line for line in rpi) </code></pre> <p>You can already iterate over the file object without this intermediate step.</p>
0
2009-01-27T00:40:43Z
[ "python", "text-processing" ]
Extracting info from large structured text files
481,862
<p>I need to read some large files (from 50k to 100k lines), structured in groups separated by empty lines. Each group start at the same pattern "No.999999999 dd/mm/yyyy ZZZ". Here´s some sample data.</p> <blockquote> <p>No.813829461 16/09/1987 270<br /> Tit.SUZANO PAPEL E CELULOSE S.A. (BR/BA)<br /> C.N.P.J./C.I.C./N INPI : 16404287000155<br /> Procurador: MARCELLO DO NASCIMENTO </p> <p>No.815326777 28/12/1989 351<br /> Tit.SIGLA SISTEMA GLOBO DE GRAVACOES AUDIO VISUAIS LTDA (BR/RJ)<br /> C.N.P.J./C.I.C./NºINPI : 34162651000108<br /> Apres.: Nominativa ; Nat.: De Produto<br /> Marca: TRIO TROPICAL<br /> Clas.Prod/Serv: 09.40<br /> *DEFERIDO CONFORME RESOLUÇÃO 123 DE 06/01/2006, PUBLICADA NA RPI 1829, DE 24/01/2006.<br /> Procurador: WALDEMAR RODRIGUES PEDRA </p> <p>No.900148764 11/01/2007 LD3<br /> Tit.TIARA BOLSAS E CALÇADOS LTDA<br /> Procurador: Marcia Ferreira Gomes<br /> *Escritório: Marcas Marcantes e Patentes Ltda<br /> *Exigência Formal não respondida Satisfatoriamente, Pedido de Registro de Marca considerado inexistente, de acordo com Art. 157 da LPI<br /> *Protocolo da Petição de cumprimento de Exigência Formal: 810080140197</p> </blockquote> <p>I wrote some code that´s parsing it accordingly. There´s anything that I can improve, to improve readability or performance? Here´s what I come so far:</p> <pre><code>import re, pprint class Despacho(object): """ Class to parse each line, applying the regexp and storing the results for future use """ regexp = { re.compile(r'No.([\d]{9}) ([\d]{2}/[\d]{2}/[\d]{4}) (.*)'): lambda self: self._processo, re.compile(r'Tit.(.*)'): lambda self: self._titular, re.compile(r'Procurador: (.*)'): lambda self: self._procurador, re.compile(r'C.N.P.J./C.I.C./N INPI :(.*)'): lambda self: self._documento, re.compile(r'Apres.: (.*) ; Nat.: (.*)'): lambda self: self._apresentacao, re.compile(r'Marca: (.*)'): lambda self: self._marca, re.compile(r'Clas.Prod/Serv: (.*)'): lambda self: self._classe, re.compile(r'\*(.*)'): lambda self: self._complemento, } def __init__(self): """ 'complemento' is the only field that can be multiple in a single registry """ self.complemento = [] def _processo(self, matches): self.processo, self.data, self.despacho = matches.groups() def _titular(self, matches): self.titular = matches.group(1) def _procurador(self, matches): self.procurador = matches.group(1) def _documento(self, matches): self.documento = matches.group(1) def _apresentacao(self, matches): self.apresentacao, self.natureza = matches.groups() def _marca(self, matches): self.marca = matches.group(1) def _classe(self, matches): self.classe = matches.group(1) def _complemento(self, matches): self.complemento.append(matches.group(1)) def read(self, line): for pattern in Despacho.regexp: m = pattern.match(line) if m: Despacho.regexp[pattern](self)(m) def process(rpi): """ read data and process each group """ rpi = (line for line in rpi) group = False for line in rpi: if line.startswith('No.'): group = True d = Despacho() if not line.strip() and group: # empty line - end of block yield d group = False d.read(line) arquivo = open('rm1972.txt') # file to process for desp in process(arquivo): pprint.pprint(desp.__dict__) print('--------------') </code></pre> <p>Thank you.</p> <p>By the way, sorry for my poor english. :)</p>
1
2009-01-26T23:47:04Z
481,991
<p>That is pretty good. Below some suggestions, let me know if you like'em:</p> <pre><code>import re import pprint import sys class Despacho(object): """ Class to parse each line, applying the regexp and storing the results for future use """ #used a dict with the keys instead of functions. regexp = { ('processo', 'data', 'despacho'): re.compile(r'No.([\d]{9}) ([\d]{2}/[\d]{2}/[\d]{4}) (.*)'), ('titular',): re.compile(r'Tit.(.*)'), ('procurador',): re.compile(r'Procurador: (.*)'), ('documento',): re.compile(r'C.N.P.J./C.I.C./N INPI :(.*)'), ('apresentacao', 'natureza'): re.compile(r'Apres.: (.*) ; Nat.: (.*)'), ('marca',): re.compile(r'Marca: (.*)'), ('classe',): re.compile(r'Clas.Prod/Serv: (.*)'), ('complemento',): re.compile(r'\*(.*)'), } def __init__(self): """ 'complemento' is the only field that can be multiple in a single registry """ self.complemento = [] def read(self, line): for attrs, pattern in Despacho.regexp.iteritems(): m = pattern.match(line) if m: for groupn, attr in enumerate(attrs): # special case complemento: if attr == 'complemento': self.complemento.append(m.group(groupn + 1)) else: # set the attribute on the object setattr(self, attr, m.group(groupn + 1)) def __repr__(self): # defines object printed representation d = {} for attrs in self.regexp: for attr in attrs: d[attr] = getattr(self, attr, None) return pprint.pformat(d) def process(rpi): """ read data and process each group """ #Useless line, since you're doing a for anyway #rpi = (line for line in rpi) group = False for line in rpi: if line.startswith('No.'): group = True d = Despacho() if not line.strip() and group: # empty line - end of block yield d group = False d.read(line) def main(): arquivo = open('rm1972.txt') # file to process for desp in process(arquivo): print desp # can print directly here. print('-' * 20) return 0 if __name__ == '__main__': main() </code></pre>
2
2009-01-27T00:55:51Z
[ "python", "text-processing" ]
Extracting info from large structured text files
481,862
<p>I need to read some large files (from 50k to 100k lines), structured in groups separated by empty lines. Each group start at the same pattern "No.999999999 dd/mm/yyyy ZZZ". Here´s some sample data.</p> <blockquote> <p>No.813829461 16/09/1987 270<br /> Tit.SUZANO PAPEL E CELULOSE S.A. (BR/BA)<br /> C.N.P.J./C.I.C./N INPI : 16404287000155<br /> Procurador: MARCELLO DO NASCIMENTO </p> <p>No.815326777 28/12/1989 351<br /> Tit.SIGLA SISTEMA GLOBO DE GRAVACOES AUDIO VISUAIS LTDA (BR/RJ)<br /> C.N.P.J./C.I.C./NºINPI : 34162651000108<br /> Apres.: Nominativa ; Nat.: De Produto<br /> Marca: TRIO TROPICAL<br /> Clas.Prod/Serv: 09.40<br /> *DEFERIDO CONFORME RESOLUÇÃO 123 DE 06/01/2006, PUBLICADA NA RPI 1829, DE 24/01/2006.<br /> Procurador: WALDEMAR RODRIGUES PEDRA </p> <p>No.900148764 11/01/2007 LD3<br /> Tit.TIARA BOLSAS E CALÇADOS LTDA<br /> Procurador: Marcia Ferreira Gomes<br /> *Escritório: Marcas Marcantes e Patentes Ltda<br /> *Exigência Formal não respondida Satisfatoriamente, Pedido de Registro de Marca considerado inexistente, de acordo com Art. 157 da LPI<br /> *Protocolo da Petição de cumprimento de Exigência Formal: 810080140197</p> </blockquote> <p>I wrote some code that´s parsing it accordingly. There´s anything that I can improve, to improve readability or performance? Here´s what I come so far:</p> <pre><code>import re, pprint class Despacho(object): """ Class to parse each line, applying the regexp and storing the results for future use """ regexp = { re.compile(r'No.([\d]{9}) ([\d]{2}/[\d]{2}/[\d]{4}) (.*)'): lambda self: self._processo, re.compile(r'Tit.(.*)'): lambda self: self._titular, re.compile(r'Procurador: (.*)'): lambda self: self._procurador, re.compile(r'C.N.P.J./C.I.C./N INPI :(.*)'): lambda self: self._documento, re.compile(r'Apres.: (.*) ; Nat.: (.*)'): lambda self: self._apresentacao, re.compile(r'Marca: (.*)'): lambda self: self._marca, re.compile(r'Clas.Prod/Serv: (.*)'): lambda self: self._classe, re.compile(r'\*(.*)'): lambda self: self._complemento, } def __init__(self): """ 'complemento' is the only field that can be multiple in a single registry """ self.complemento = [] def _processo(self, matches): self.processo, self.data, self.despacho = matches.groups() def _titular(self, matches): self.titular = matches.group(1) def _procurador(self, matches): self.procurador = matches.group(1) def _documento(self, matches): self.documento = matches.group(1) def _apresentacao(self, matches): self.apresentacao, self.natureza = matches.groups() def _marca(self, matches): self.marca = matches.group(1) def _classe(self, matches): self.classe = matches.group(1) def _complemento(self, matches): self.complemento.append(matches.group(1)) def read(self, line): for pattern in Despacho.regexp: m = pattern.match(line) if m: Despacho.regexp[pattern](self)(m) def process(rpi): """ read data and process each group """ rpi = (line for line in rpi) group = False for line in rpi: if line.startswith('No.'): group = True d = Despacho() if not line.strip() and group: # empty line - end of block yield d group = False d.read(line) arquivo = open('rm1972.txt') # file to process for desp in process(arquivo): pprint.pprint(desp.__dict__) print('--------------') </code></pre> <p>Thank you.</p> <p>By the way, sorry for my poor english. :)</p>
1
2009-01-26T23:47:04Z
484,866
<p>I wouldn't use regex here. If you know that your lines will be starting with fixed strings, why not check those strings and write a logic around it?</p> <pre><code>for line in open(file): if line[0:3]=='No.': currIndex='No' map['No']=line[4:] .... ... else if line.strip()=='': //store the record in the map and clear the map else: //append line to the last index in map.. this is when the record overflows to the next line. Map[currIndex]=Map[currIndex]+"\n"+line </code></pre> <p>Consider the above code as just the pseudocode.</p>
0
2009-01-27T19:29:55Z
[ "python", "text-processing" ]
Extracting info from large structured text files
481,862
<p>I need to read some large files (from 50k to 100k lines), structured in groups separated by empty lines. Each group start at the same pattern "No.999999999 dd/mm/yyyy ZZZ". Here´s some sample data.</p> <blockquote> <p>No.813829461 16/09/1987 270<br /> Tit.SUZANO PAPEL E CELULOSE S.A. (BR/BA)<br /> C.N.P.J./C.I.C./N INPI : 16404287000155<br /> Procurador: MARCELLO DO NASCIMENTO </p> <p>No.815326777 28/12/1989 351<br /> Tit.SIGLA SISTEMA GLOBO DE GRAVACOES AUDIO VISUAIS LTDA (BR/RJ)<br /> C.N.P.J./C.I.C./NºINPI : 34162651000108<br /> Apres.: Nominativa ; Nat.: De Produto<br /> Marca: TRIO TROPICAL<br /> Clas.Prod/Serv: 09.40<br /> *DEFERIDO CONFORME RESOLUÇÃO 123 DE 06/01/2006, PUBLICADA NA RPI 1829, DE 24/01/2006.<br /> Procurador: WALDEMAR RODRIGUES PEDRA </p> <p>No.900148764 11/01/2007 LD3<br /> Tit.TIARA BOLSAS E CALÇADOS LTDA<br /> Procurador: Marcia Ferreira Gomes<br /> *Escritório: Marcas Marcantes e Patentes Ltda<br /> *Exigência Formal não respondida Satisfatoriamente, Pedido de Registro de Marca considerado inexistente, de acordo com Art. 157 da LPI<br /> *Protocolo da Petição de cumprimento de Exigência Formal: 810080140197</p> </blockquote> <p>I wrote some code that´s parsing it accordingly. There´s anything that I can improve, to improve readability or performance? Here´s what I come so far:</p> <pre><code>import re, pprint class Despacho(object): """ Class to parse each line, applying the regexp and storing the results for future use """ regexp = { re.compile(r'No.([\d]{9}) ([\d]{2}/[\d]{2}/[\d]{4}) (.*)'): lambda self: self._processo, re.compile(r'Tit.(.*)'): lambda self: self._titular, re.compile(r'Procurador: (.*)'): lambda self: self._procurador, re.compile(r'C.N.P.J./C.I.C./N INPI :(.*)'): lambda self: self._documento, re.compile(r'Apres.: (.*) ; Nat.: (.*)'): lambda self: self._apresentacao, re.compile(r'Marca: (.*)'): lambda self: self._marca, re.compile(r'Clas.Prod/Serv: (.*)'): lambda self: self._classe, re.compile(r'\*(.*)'): lambda self: self._complemento, } def __init__(self): """ 'complemento' is the only field that can be multiple in a single registry """ self.complemento = [] def _processo(self, matches): self.processo, self.data, self.despacho = matches.groups() def _titular(self, matches): self.titular = matches.group(1) def _procurador(self, matches): self.procurador = matches.group(1) def _documento(self, matches): self.documento = matches.group(1) def _apresentacao(self, matches): self.apresentacao, self.natureza = matches.groups() def _marca(self, matches): self.marca = matches.group(1) def _classe(self, matches): self.classe = matches.group(1) def _complemento(self, matches): self.complemento.append(matches.group(1)) def read(self, line): for pattern in Despacho.regexp: m = pattern.match(line) if m: Despacho.regexp[pattern](self)(m) def process(rpi): """ read data and process each group """ rpi = (line for line in rpi) group = False for line in rpi: if line.startswith('No.'): group = True d = Despacho() if not line.strip() and group: # empty line - end of block yield d group = False d.read(line) arquivo = open('rm1972.txt') # file to process for desp in process(arquivo): pprint.pprint(desp.__dict__) print('--------------') </code></pre> <p>Thank you.</p> <p>By the way, sorry for my poor english. :)</p>
1
2009-01-26T23:47:04Z
485,417
<p>Another version with only one combined regular expression:</p> <pre><code>#!/usr/bin/python import re import pprint import sys class Despacho(object): """ Class to parse each line, applying the regexp and storing the results for future use """ #used a dict with the keys instead of functions. regexp = re.compile( r'No.(?P&lt;processo&gt;[\d]{9}) (?P&lt;data&gt;[\d]{2}/[\d]{2}/[\d]{4}) (?P&lt;despacho&gt;.*)' r'|Tit.(?P&lt;titular&gt;.*)' r'|Procurador: (?P&lt;procurador&gt;.*)' r'|C.N.P.J./C.I.C./N INPI :(?P&lt;documento&gt;.*)' r'|Apres.: (?P&lt;apresentacao&gt;.*) ; Nat.: (?P&lt;natureza&gt;.*)' r'|Marca: (?P&lt;marca&gt;.*)' r'|Clas.Prod/Serv: (?P&lt;classe&gt;.*)' r'|\*(?P&lt;complemento&gt;.*)') simplefields = ('processo', 'data', 'despacho', 'titular', 'procurador', 'documento', 'apresentacao', 'natureza', 'marca', 'classe') def __init__(self): """ 'complemento' is the only field that can be multiple in a single registry """ self.__dict__ = dict.fromkeys(self.simplefields) self.complemento = [] def parse(self, line): m = self.regexp.match(line) if m: gd = dict((k, v) for k, v in m.groupdict().items() if v) if 'complemento' in gd: self.complemento.append(gd['complemento']) else: self.__dict__.update(gd) def __repr__(self): # defines object printed representation return pprint.pformat(self.__dict__) def process(rpi): """ read data and process each group """ d = None for line in rpi: if line.startswith('No.'): if d: yield d d = Despacho() d.parse(line) yield d def main(): arquivo = file('rm1972.txt') # file to process for desp in process(arquivo): print desp # can print directly here. print '-' * 20 if __name__ == '__main__': main() </code></pre>
0
2009-01-27T21:42:46Z
[ "python", "text-processing" ]