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
listlengths
1
5
Efficient storage of and access to web pages with Python
1,548,857
<p>So like many people I want a way to download, index/extract information and store web pages efficiently. My first thought is to use MySQL and simply shove the pages in which would let me use FULLTEXT searches which would let me do ad hoc queries easily (in case I want to see if something exists and extract it/etc.)....
1
2009-10-10T19:29:56Z
1,548,911
<p>Why do you think solution (3), the Sphinx-based one, requires "repeatedly crawling the site"? Sphinx can accept and index many different data sources, including MySQL and PostgreSQL "natively" (there are contributed add-ons for other DBs such as Firebird) -- you can keep your HTML docs as columns in your DB if you ...
2
2009-10-10T19:56:50Z
[ "python", "mysql", "database" ]
Generate a string representation of a one-hot encoding
1,548,984
<p>In Python, I need to generate a <code>dict</code> that maps a letter to a pre-defined "<a href="http://en.wikipedia.org/wiki/One-hot" rel="nofollow">one-hot</a>" representation of that letter. By way of illustration, the <code>dict</code> should look like this:</p> <pre><code>{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...
3
2009-10-10T20:22:06Z
1,548,988
<p>That seems pretty clear, concise, and Pythonic to me.</p>
0
2009-10-10T20:23:28Z
[ "python", "data-generation" ]
Generate a string representation of a one-hot encoding
1,548,984
<p>In Python, I need to generate a <code>dict</code> that maps a letter to a pre-defined "<a href="http://en.wikipedia.org/wiki/One-hot" rel="nofollow">one-hot</a>" representation of that letter. By way of illustration, the <code>dict</code> should look like this:</p> <pre><code>{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...
3
2009-10-10T20:22:06Z
1,549,010
<pre><code>one_hot = [' '.join(['0']*a + ['1'] + ['0']*b) for a, b in zip(range(n), range(n-1, -1, -1))] outputs = dict(zip(_letters, one_hot)) </code></pre> <p>In particular, there's a <em>lot</em> of code packed into these two lines. You might try the <a href="http://www.refactoring.com/catalog/introduc...
1
2009-10-10T20:36:44Z
[ "python", "data-generation" ]
Generate a string representation of a one-hot encoding
1,548,984
<p>In Python, I need to generate a <code>dict</code> that maps a letter to a pre-defined "<a href="http://en.wikipedia.org/wiki/One-hot" rel="nofollow">one-hot</a>" representation of that letter. By way of illustration, the <code>dict</code> should look like this:</p> <pre><code>{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...
3
2009-10-10T20:22:06Z
1,549,021
<p>I find this to be more readable:</p> <pre><code>from string import ascii_uppercase one_hot = {} for i, l in enumerate(ascii_uppercase): bits = ['0']*26; bits[i] = '1' one_hot[l] = ' '.join(bits) </code></pre> <p>If you need a more general alphabet, just enumerate over a string of the characters, and repla...
6
2009-10-10T20:40:29Z
[ "python", "data-generation" ]
Generate a string representation of a one-hot encoding
1,548,984
<p>In Python, I need to generate a <code>dict</code> that maps a letter to a pre-defined "<a href="http://en.wikipedia.org/wiki/One-hot" rel="nofollow">one-hot</a>" representation of that letter. By way of illustration, the <code>dict</code> should look like this:</p> <pre><code>{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...
3
2009-10-10T20:22:06Z
1,549,091
<p>In Python 2.5 and up you can use the conditional operator:</p> <pre><code>from string import ascii_uppercase one_hot = {} for i, c in enumerate(ascii_uppercase): one_hot[c] = ' '.join('1' if j == i else '0' for j in range(26)) </code></pre>
2
2009-10-10T21:13:39Z
[ "python", "data-generation" ]
How to set an nonexistent field in Python ClientForm?
1,548,996
<p>I'm using mechanize (which uses clientform) for some web crawling in python and since it doesn't support JS, I want to set a value of an unexistent input in a form (the input is generated by JS). How can I do this?</p> <p>The error is similar to the one you get if you try to execute</p> <pre><code>from mechanize i...
5
2009-10-10T20:29:30Z
1,549,036
<p>You need to first add the control to the form, and then <code>fixup</code> the form.</p> <pre><code>br.form.new_control('text','unexistent',{'value':''}) br.form.fixup() br['unexistent'] = 'hello' </code></pre> <p>This really isn't very well documented, and in the source under <code>fixup()</code> there is the com...
14
2009-10-10T20:45:03Z
[ "python", "mechanize", "clientform" ]
how to define a widget in a model attribute
1,549,011
<p>Simply, I write:</p> <pre><code># forms.py class NoteForm(ModelForm): def __init__(self, *args, **kwargs): super(NoteForm, self).__init__(*args, **kwargs) #add attributes to html-field-tag: self.fields['content'].widget.attrs['rows'] = 3 self.fields['title'].widget.attrs['size'] = 20 class Meta: ...
0
2009-10-10T20:37:19Z
1,549,040
<p>No, you still do it in a form, but you just pass that form as a parameter to <code>inlineformset_factory</code>.</p> <pre><code>NotesFormSet = inlineformset_factory(NoteBook, Note, extra=10, form=NoteForm) </code></pre>
1
2009-10-10T20:47:14Z
[ "python", "django", "django-forms" ]
Sorting a heterogeneous list of objects in Python
1,549,037
<p>I have some custom objects and dictionaries that I want to sort. I want to sort both the objects the dictionaries together. I want to sort the objects by an attribute and the dictionaries by a key.</p> <pre><code>object.name = 'Jack' d = {'name':'Jill'} sort_me =[object, d] </code></pre> <p>How do I sort this l...
5
2009-10-10T20:45:18Z
1,549,049
<p>What you are almost certainly looking for is to use the key= option for sorted(), which provides a function which returns an arbitrary sort key for each element. This function can check the type of its argument and take various actions. For instance:</p> <pre><code>import types class obj(object): def __init__(...
8
2009-10-10T20:51:57Z
[ "python", "sorting" ]
Sorting a heterogeneous list of objects in Python
1,549,037
<p>I have some custom objects and dictionaries that I want to sort. I want to sort both the objects the dictionaries together. I want to sort the objects by an attribute and the dictionaries by a key.</p> <pre><code>object.name = 'Jack' d = {'name':'Jill'} sort_me =[object, d] </code></pre> <p>How do I sort this l...
5
2009-10-10T20:45:18Z
1,549,085
<pre><code>sort_me.sort(key=attr_or_itemgetter('name')) </code></pre> <p>Where <code>attr_or_itemgetter()</code>:</p> <pre><code>class attr_or_itemgetter(object): def __init__(self, name): self.name = name def __call__(self, obj): try: return getattr(obj, name) except AttributeError: ...
2
2009-10-10T21:09:35Z
[ "python", "sorting" ]
Sorting a heterogeneous list of objects in Python
1,549,037
<p>I have some custom objects and dictionaries that I want to sort. I want to sort both the objects the dictionaries together. I want to sort the objects by an attribute and the dictionaries by a key.</p> <pre><code>object.name = 'Jack' d = {'name':'Jill'} sort_me =[object, d] </code></pre> <p>How do I sort this l...
5
2009-10-10T20:45:18Z
8,108,722
<p>This worked for me. Note that <code>sort()</code> does not return the sorted list, but <code>sorted()</code> does, so if you want to pass this to a template, you should use <code>sorted</code> in the parameters, or <code>sort</code> before you pass the list as a parameter.</p> <pre><code>itemized_action_list = lis...
1
2011-11-13T00:47:25Z
[ "python", "sorting" ]
Adding to local namespace in Python?
1,549,201
<p>Is there a way in Python to add to the locals name-space by calling a function without explicitly assigning variables locally?</p> <p>Something like the following for example (which of course doesn't work, because locals() return a copy of the local name-space) where the print statement would print '1'.</p> <pre><...
4
2009-10-10T22:05:05Z
1,549,221
<p>In Python <code>2.*</code>, you can disable the normal optimizations performed by the Python compiler regarding local variable access by starting your function with <code>exec ''</code>; this will make the function very much slower (I just posted, earlier today, an answer showing how the local-variable optimization ...
4
2009-10-10T22:12:26Z
[ "python", "namespaces", "class", "methods" ]
Adding to local namespace in Python?
1,549,201
<p>Is there a way in Python to add to the locals name-space by calling a function without explicitly assigning variables locally?</p> <p>Something like the following for example (which of course doesn't work, because locals() return a copy of the local name-space) where the print statement would print '1'.</p> <pre><...
4
2009-10-10T22:05:05Z
1,550,364
<p>Seems pretty horrible to rely on a hack like <code>exec ''</code>. What about communicating like this with the global statement, it seems to work:</p> <pre><code>&gt;&gt;&gt; def outer(): ... global x ... b() ... print x ... &gt;&gt;&gt; def b(): ... global x ... x = 2 ... &gt;&gt;&gt; outer() 2 </code>...
1
2009-10-11T10:31:00Z
[ "python", "namespaces", "class", "methods" ]
Grouping data points into series
1,549,412
<p>I have a series of data points (tuples) in a list with a format like:</p> <pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] </code></pre> <p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p> <p>I need them...
0
2009-10-10T23:53:56Z
1,549,425
<p>One way to do it (no promises on speed):</p> <p>Break your list of tuples into two lists: <code>[1,2,2,3,4]</code> and <code>['a','b','a','d','c']</code></p> <p>Since the first list is sorted, you can just keep iterating over it until you get to an element out of the range. Then, you know the indexes of the start ...
2
2009-10-11T00:02:23Z
[ "python", "algorithm", "series" ]
Grouping data points into series
1,549,412
<p>I have a series of data points (tuples) in a list with a format like:</p> <pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] </code></pre> <p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p> <p>I need them...
0
2009-10-10T23:53:56Z
1,549,430
<p>Your code is O(n<sup>2</sup>). Here's an O(n) solution:</p> <pre><code>def split_series(points, interval): series = [] current_group = [] marker = points[0][0] for value, data in points: if value &gt;= marker + interval: series.append(current_group) current_group = [...
2
2009-10-11T00:06:01Z
[ "python", "algorithm", "series" ]
Grouping data points into series
1,549,412
<p>I have a series of data points (tuples) in a list with a format like:</p> <pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] </code></pre> <p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p> <p>I need them...
0
2009-10-10T23:53:56Z
1,549,441
<p>From your code, I'm assuming my prior comment is correct. The problem here appears to be that the performance is O(n^2) - you repeat the list comprehension (which iterates all items) multiple times.</p> <p>I say, use a simple for loop. If the current item belongs in the same group as the previous one, add it to the...
1
2009-10-11T00:11:51Z
[ "python", "algorithm", "series" ]
Grouping data points into series
1,549,412
<p>I have a series of data points (tuples) in a list with a format like:</p> <pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] </code></pre> <p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p> <p>I need them...
0
2009-10-10T23:53:56Z
1,549,451
<p>Expanding on Am's answer, use a defaultdict, and floor-divide the key by the interval to break them up correctly.</p> <pre><code>from collections import defaultdict def split_series(points, interval): vals = defaultdict(list) for key, value in points: vals[(key-1)//interval].append(value) return...
1
2009-10-11T00:16:34Z
[ "python", "algorithm", "series" ]
Grouping data points into series
1,549,412
<p>I have a series of data points (tuples) in a list with a format like:</p> <pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] </code></pre> <p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p> <p>I need them...
0
2009-10-10T23:53:56Z
1,549,466
<p>For completeness, here's a solution with <code>itertools.groupby</code>, but the dictionary solution will probably be faster (not to mention a lot easier to read).</p> <pre><code>import itertools import operator def split_series(points, interval): start = points[0][0] return [[v for k, v in grouper] for g...
2
2009-10-11T00:23:40Z
[ "python", "algorithm", "series" ]
Grouping data points into series
1,549,412
<p>I have a series of data points (tuples) in a list with a format like:</p> <pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] </code></pre> <p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p> <p>I need them...
0
2009-10-10T23:53:56Z
1,549,467
<p>How about using iterators for lazy evaluation?</p> <p>This should be the equivalent of your initial solution:</p> <pre><code>from itertools import groupby def split_series(points, interval): """ &gt;&gt;&gt; points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] &gt;&gt;&gt; print list(split_seri...
0
2009-10-11T00:25:13Z
[ "python", "algorithm", "series" ]
Grouping data points into series
1,549,412
<p>I have a series of data points (tuples) in a list with a format like:</p> <pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')] </code></pre> <p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p> <p>I need them...
0
2009-10-10T23:53:56Z
1,561,542
<p>Here's a lazy approach that uses the step behavior of xrange:</p> <pre><code>def split_series(points, interval): end_of_chunk = interval chunk = [] for marker, item in points: if marker &gt; end_of_chunk: for end_of_chunk in xrange(end_of_chunk, marker, interval): yie...
1
2009-10-13T16:57:37Z
[ "python", "algorithm", "series" ]
Separately validating username and password during Django authentication
1,549,442
<p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p> <ul> <li>Username was valid, password was invalid</li> <li>Username was invalid</li> </ul> <p>I am thinking that I would like...
5
2009-10-11T00:11:56Z
1,549,508
<p>We had to deal with this on a site that used an external membership subscription service. Basically you do</p> <pre><code>from django.contrib.auth.models import User try: user = User.objects.get(username=whatever) # if you get here the username exists and you can do a normal authentication except: pass...
0
2009-10-11T00:49:14Z
[ "python", "django", "security", "authentication" ]
Separately validating username and password during Django authentication
1,549,442
<p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p> <ul> <li>Username was valid, password was invalid</li> <li>Username was invalid</li> </ul> <p>I am thinking that I would like...
5
2009-10-11T00:11:56Z
1,549,582
<p>You really don't want to distinguish between these two cases. Otherwise, you are giving a potential hacker a clue as to whether or not a username is valid - a significant help towards gaining a fraudulent login.</p>
19
2009-10-11T01:29:45Z
[ "python", "django", "security", "authentication" ]
Separately validating username and password during Django authentication
1,549,442
<p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p> <ul> <li>Username was valid, password was invalid</li> <li>Username was invalid</li> </ul> <p>I am thinking that I would like...
5
2009-10-11T00:11:56Z
1,552,067
<p>This is not a function of the backend simply the authentication form. Just rewrite the form to display the errors you want for each field. Write a login view that use your new form and make that the default login url. (Actually I just saw in a recent commit of Django you can now pass a custom form to the login view,...
2
2009-10-11T23:23:54Z
[ "python", "django", "security", "authentication" ]
Separately validating username and password during Django authentication
1,549,442
<p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p> <ul> <li>Username was valid, password was invalid</li> <li>Username was invalid</li> </ul> <p>I am thinking that I would like...
5
2009-10-11T00:11:56Z
1,552,085
<p>This answer is not specific to Django, but this is the pseudo-code I would use to accomplish this:</p> <pre><code>//Query if user exists who's username=&lt;username&gt; and password=&lt;password&gt; //If true //successful login! //If false //Query if user exists who's username=&lt;username&gt; //I...
0
2009-10-11T23:33:09Z
[ "python", "django", "security", "authentication" ]
Separately validating username and password during Django authentication
1,549,442
<p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p> <ul> <li>Username was valid, password was invalid</li> <li>Username was invalid</li> </ul> <p>I am thinking that I would like...
5
2009-10-11T00:11:56Z
3,743,636
<pre><code>def clean_username(self): """ Verifies that the username is available. """ username = self.cleaned_data["username"] try: user = User.objects.get(username=username) except User.DoesNotExist: return username else: raise forms.ValidationError(u"""\ ...
0
2010-09-18T21:48:11Z
[ "python", "django", "security", "authentication" ]
How do do this list manipulation in Python? This is tricky
1,549,445
<p>Suppose I have this list:</p> <pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] </code></pre> <p>What is the MOST efficient way to turn it into this list?</p> <pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] </code></pre> <p>Notice, I grab the first from each. Then the 2nd element from each. Of course, this ...
2
2009-10-11T00:13:38Z
1,549,455
<pre><code>&gt;&gt;&gt; L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] &gt;&gt;&gt; L2 = [] &gt;&gt;&gt; map(L2.extend, zip(*L1)) &gt;&gt;&gt; L2 [5, 7, 1, 44, 21, 32, 73, 99, 100] </code></pre>
10
2009-10-11T00:18:03Z
[ "python", "list" ]
How do do this list manipulation in Python? This is tricky
1,549,445
<p>Suppose I have this list:</p> <pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] </code></pre> <p>What is the MOST efficient way to turn it into this list?</p> <pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] </code></pre> <p>Notice, I grab the first from each. Then the 2nd element from each. Of course, this ...
2
2009-10-11T00:13:38Z
1,549,459
<p>As long as all sublists are the same length:</p> <pre><code>def flattener(nestedlist): if not nestedlist: return [] return [ x for i in range(len(nestedlist[0])) for x in [sublist[i] for sublist in nestedlist] ] </code></pre> <p>For example,</p> <pre><code>print flattener([ [5, 44, 73] ,...
2
2009-10-11T00:21:23Z
[ "python", "list" ]
How do do this list manipulation in Python? This is tricky
1,549,445
<p>Suppose I have this list:</p> <pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] </code></pre> <p>What is the MOST efficient way to turn it into this list?</p> <pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] </code></pre> <p>Notice, I grab the first from each. Then the 2nd element from each. Of course, this ...
2
2009-10-11T00:13:38Z
1,549,463
<p>Here is an O^2 solution, it assumes all the inner arrays are of the same length</p> <pre><code>parent = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] final = [] for i in range(len(parent[0])): for x in range(len(parent)): final.append(parent[x][i]) print final # [5, 7, 1, 44, 21, 32, 73, 99, 100] </code></pr...
0
2009-10-11T00:22:11Z
[ "python", "list" ]
How do do this list manipulation in Python? This is tricky
1,549,445
<p>Suppose I have this list:</p> <pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] </code></pre> <p>What is the MOST efficient way to turn it into this list?</p> <pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] </code></pre> <p>Notice, I grab the first from each. Then the 2nd element from each. Of course, this ...
2
2009-10-11T00:13:38Z
1,549,468
<p>As long as all the sublists are of the same length:</p> <pre><code>lst = [[5, 44, 73] , [7, 21, 99], [1, 32, 100]] list(reduce(lambda l, r: l + r, zip(*lst))) </code></pre> <p>Edit: This will work with sublists of different lengths:</p> <pre><code>lst = [[5, 44, 73, 23] , [7, 21, 99], [1, 32, 100]] list(filter(la...
-2
2009-10-11T00:25:35Z
[ "python", "list" ]
How do do this list manipulation in Python? This is tricky
1,549,445
<p>Suppose I have this list:</p> <pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] </code></pre> <p>What is the MOST efficient way to turn it into this list?</p> <pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] </code></pre> <p>Notice, I grab the first from each. Then the 2nd element from each. Of course, this ...
2
2009-10-11T00:13:38Z
1,549,482
<pre><code>import itertools list(itertools.chain(*zip(*L1))) </code></pre> <p>If you need lists of varying length:</p> <pre><code>import itertools [x for x in itertools.chain(*itertools.izip_longest(*L1)) if x is not None] </code></pre>
8
2009-10-11T00:33:01Z
[ "python", "list" ]
How do do this list manipulation in Python? This is tricky
1,549,445
<p>Suppose I have this list:</p> <pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] </code></pre> <p>What is the MOST efficient way to turn it into this list?</p> <pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] </code></pre> <p>Notice, I grab the first from each. Then the 2nd element from each. Of course, this ...
2
2009-10-11T00:13:38Z
1,549,489
<p>A simple list comprehension to the second depth:</p> <pre><code>&gt;&gt;&gt; L = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] &gt;&gt;&gt; [x for li in zip(*L) for x in li] [5, 7, 1, 44, 21, 32, 73, 99, 100] </code></pre> <p>pretty nice. If the sublists are of uneven length, it is not as elegant to express:</p> <p...
0
2009-10-11T00:37:36Z
[ "python", "list" ]
How do do this list manipulation in Python? This is tricky
1,549,445
<p>Suppose I have this list:</p> <pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] </code></pre> <p>What is the MOST efficient way to turn it into this list?</p> <pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] </code></pre> <p>Notice, I grab the first from each. Then the 2nd element from each. Of course, this ...
2
2009-10-11T00:13:38Z
1,549,521
<p>"One-liner" != "Pythonic"</p> <p>It is <em>bad</em> form to use a list comprehension just to implement a for loop in one line. Save the list expressions or generator expressions for times when you want the results of the expression. The clearest and most Pythonic to my eye is (for sublists of equal length):</p> ...
4
2009-10-11T00:56:17Z
[ "python", "list" ]
How do do this list manipulation in Python? This is tricky
1,549,445
<p>Suppose I have this list:</p> <pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] </code></pre> <p>What is the MOST efficient way to turn it into this list?</p> <pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ] </code></pre> <p>Notice, I grab the first from each. Then the 2nd element from each. Of course, this ...
2
2009-10-11T00:13:38Z
1,549,616
<pre><code>&gt;&gt;&gt; L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ] &gt;&gt;&gt; L2 = list(sum(zip(*L1), ())) &gt;&gt;&gt; L2 [5, 7, 1, 44, 21, 32, 73, 99, 100] </code></pre>
1
2009-10-11T01:48:35Z
[ "python", "list" ]
Remove duplicates in a list while keeping its order (Python)
1,549,509
<p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-i...
19
2009-10-11T00:49:35Z
1,549,520
<p>A super easy way to do this is:</p> <pre><code>def uniq(a): if len(a) == 0: return [] else: return [a[0]] + uniq([x for x in a if x != a[0]]) </code></pre> <p>This is not the most efficient way, because:</p> <ul> <li>it searches through the whole list for every element in the list, so it's...
0
2009-10-11T00:55:38Z
[ "python", "list" ]
Remove duplicates in a list while keeping its order (Python)
1,549,509
<p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-i...
19
2009-10-11T00:49:35Z
1,549,523
<p>This page discusses different methods and their speeds: <a href="http://www.peterbe.com/plog/uniqifiers-benchmark" rel="nofollow">http://www.peterbe.com/plog/uniqifiers-benchmark</a></p> <p>The recommended* method:</p> <pre><code>def f5(seq, idfun=None): # order preserving if idfun is None: def...
3
2009-10-11T00:56:46Z
[ "python", "list" ]
Remove duplicates in a list while keeping its order (Python)
1,549,509
<p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-i...
19
2009-10-11T00:49:35Z
1,549,527
<pre><code>dups = {} newlist = [] for x in biglist: if x['link'] not in dups: newlist.append(x) dups[x['link']] = None print newlist </code></pre> <p>produces</p> <pre><code>[{'link': 'u2.com', 'title': 'U2 Band'}, {'link': 'abc.com', 'title': 'ABC Station'}] </code></pre> <p>Note that here I used a...
1
2009-10-11T00:59:11Z
[ "python", "list" ]
Remove duplicates in a list while keeping its order (Python)
1,549,509
<p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-i...
19
2009-10-11T00:49:35Z
1,549,530
<p>I think using a set should be pretty efficent.</p> <pre><code>seen_links = set() for index in len(biglist): link = biglist[index]['link'] if link in seen_links: del(biglist[index]) seen_links.add(link) </code></pre> <p>I think this should come in at O(nlog(n))</p>
0
2009-10-11T00:59:49Z
[ "python", "list" ]
Remove duplicates in a list while keeping its order (Python)
1,549,509
<p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-i...
19
2009-10-11T00:49:35Z
1,549,549
<p>My answer to your other question, which you completely ignored!, shows you're wrong in claiming that </p> <blockquote> <p>The answers of that question did not keep the "order"</p> </blockquote> <ul> <li>my answer <strong>did</strong> keep order, and it clearly <strong>said</strong> it did. Here it is again, ...
20
2009-10-11T01:11:15Z
[ "python", "list" ]
Remove duplicates in a list while keeping its order (Python)
1,549,509
<p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-i...
19
2009-10-11T00:49:35Z
1,549,550
<p>Generators are great.</p> <pre><code>def unique( seq ): seen = set() for item in seq: if item not in seen: seen.add( item ) yield item biglist[:] = unique( biglist ) </code></pre>
6
2009-10-11T01:11:43Z
[ "python", "list" ]
Remove duplicates in a list while keeping its order (Python)
1,549,509
<p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-i...
19
2009-10-11T00:49:35Z
9,572,193
<pre><code>list = ['aaa','aba','aaa','aea','baa','aaa','aac','aaa',] uniq = [] for i in list: if i not in uniq: uniq.append(i) print list print uniq </code></pre> <p>output will be:</p> <p>['aaa', 'aba', 'aaa', 'aea', 'baa', 'aaa', 'aac', 'aaa']</p> <p>['aaa', 'aba', 'aea', 'baa...
1
2012-03-05T18:50:55Z
[ "python", "list" ]
Remove duplicates in a list while keeping its order (Python)
1,549,509
<p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-i...
19
2009-10-11T00:49:35Z
22,520,277
<p>This is an elegant and compact way, with list comprehension (but not as efficient as with dictionary):</p> <pre><code>mylist = ['aaa','aba','aaa','aea','baa','aaa','aac','aaa',] [ v for (i,v) in enumerate(mylist) if v not in mylist[0:i] ] </code></pre> <p>And in the context of the answer:</p> <pre><code>[ v for ...
1
2014-03-19T23:20:46Z
[ "python", "list" ]
Remove duplicates in a list while keeping its order (Python)
1,549,509
<p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-i...
19
2009-10-11T00:49:35Z
25,560,184
<p>use set(), then re-sort using the index of the original list.</p> <pre><code>&gt;&gt;&gt; mylist = ['c','a','a','b','a','b','c'] &gt;&gt;&gt; sorted(set(mylist), key=lambda x: mylist.index(x)) ['c', 'a', 'b'] </code></pre>
11
2014-08-29T00:59:31Z
[ "python", "list" ]
Why does this happen in my template for Django?
1,549,606
<p>simple%20minds is displayed when do this:</p> <p>{{ rec.artist_name }}</p> <p>How do I remove the %20...and make it spaces?</p> <p>When I put | safe as a fitler, the error is:</p> <p>Could not parse the remainder: ' | safe' from 'active.artist_name | safe'</p> <p>Thanks.</p>
0
2009-10-11T01:42:40Z
1,549,618
<p>I think you're being hit by Django's relatively-new autoescaping. What happens if you do </p> <pre><code>{{ rec.artist_name | safe }} </code></pre> <p>to avid the value being autoescaped?</p>
2
2009-10-11T01:49:24Z
[ "python", "django" ]
Why does this happen in my template for Django?
1,549,606
<p>simple%20minds is displayed when do this:</p> <p>{{ rec.artist_name }}</p> <p>How do I remove the %20...and make it spaces?</p> <p>When I put | safe as a fitler, the error is:</p> <p>Could not parse the remainder: ' | safe' from 'active.artist_name | safe'</p> <p>Thanks.</p>
0
2009-10-11T01:42:40Z
1,549,656
<p>Try removing the space between the rec.artist_name and the |. So you should have this: </p> <p><code>{{ rec.artist_name|safe }}</code></p> <p>That'll fix the autoescaping, but I think the other commentors are correct in saying that you're storing the %20 into the db. So you'll probably have to fix it on that end o...
1
2009-10-11T02:09:53Z
[ "python", "django" ]
How to capitalize the first letter of each word in a string (Python)?
1,549,641
<pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be :</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
267
2009-10-11T02:03:54Z
1,549,644
<p>The <a href="http://docs.python.org/library/stdtypes.html#str.title"><code>.title()</code></a> method of a string (either ASCII or Unicode is fine) does this:</p> <pre><code>&gt;&gt;&gt; "hello world".title() 'Hello World' &gt;&gt;&gt; u"hello world".title() u'Hello World' </code></pre> <p>However, look out for st...
436
2009-10-11T02:04:35Z
[ "python", "capitalization", "capitalize" ]
How to capitalize the first letter of each word in a string (Python)?
1,549,641
<pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be :</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
267
2009-10-11T02:03:54Z
1,549,983
<p>Just because this sort of thing is fun for me, here are two more solutions.</p> <p>Split into words, initial-cap each word from the split groups, and rejoin. This will change the white space separating the words into a single white space, no matter what it was.</p> <pre><code>s = 'the brown fox' lst = [word[0].up...
62
2009-10-11T06:04:11Z
[ "python", "capitalization", "capitalize" ]
How to capitalize the first letter of each word in a string (Python)?
1,549,641
<pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be :</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
267
2009-10-11T02:03:54Z
1,549,985
<p>If str.title() doesn't work for you, do the capitalization yourself.</p> <ol> <li>Split the string into a list of words</li> <li>Capitalize the first letter of each word</li> <li>Join the words into a single string</li> </ol> <p>One-liner:</p> <pre><code>&gt;&gt;&gt; ' '.join([s[0].upper() + s[1:] for s in "they'...
6
2009-10-11T06:05:41Z
[ "python", "capitalization", "capitalize" ]
How to capitalize the first letter of each word in a string (Python)?
1,549,641
<pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be :</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
267
2009-10-11T02:03:54Z
10,013,565
<p>Copy-paste-ready version of @jibberia anwser:</p> <pre><code>def capitalize(line): return ' '.join(s[0].upper() + s[1:] for s in line.split(' ')) </code></pre>
10
2012-04-04T14:47:11Z
[ "python", "capitalization", "capitalize" ]
How to capitalize the first letter of each word in a string (Python)?
1,549,641
<pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be :</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
267
2009-10-11T02:03:54Z
12,336,911
<p>the 'title' method can't work well, </p> <pre><code>&gt;&gt;&gt; "they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk" </code></pre> <p>Try string.capwords, </p> <pre><code>import string string.capwords("they're bill's friends from the UK") &gt;&gt;&gt;"They're Bill's Friends From The ...
90
2012-09-09T06:03:36Z
[ "python", "capitalization", "capitalize" ]
How to capitalize the first letter of each word in a string (Python)?
1,549,641
<pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be :</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
267
2009-10-11T02:03:54Z
19,894,900
<p>I really like this answer:</p> <blockquote> <p>Copy-paste-ready version of @jibberia anwser:</p> <p>def capitalize(line): return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])</p> </blockquote> <p>But some of the lines that I was sending split off some blank '' characters that caused errors...
-2
2013-11-10T20:39:10Z
[ "python", "capitalization", "capitalize" ]
How to capitalize the first letter of each word in a string (Python)?
1,549,641
<pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be :</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
267
2009-10-11T02:03:54Z
21,432,975
<p>Capitalize words...</p> <pre> str = "this is string example.... wow!!!"; print "str.title() : ", str.title(); </pre>
1
2014-01-29T13:47:58Z
[ "python", "capitalization", "capitalize" ]
How to capitalize the first letter of each word in a string (Python)?
1,549,641
<pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be :</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
267
2009-10-11T02:03:54Z
22,437,210
<p>As Mark pointed out you should use <a href="http://docs.python.org/2/library/stdtypes.html#str.title" rel="nofollow"><code>.title()</code></a>:</p> <pre><code>"MyAwesomeString".title() </code></pre> <p>However, if would like to make the first letter uppercase <strong>inside a django template</strong>, you could us...
-1
2014-03-16T13:04:49Z
[ "python", "capitalization", "capitalize" ]
How to capitalize the first letter of each word in a string (Python)?
1,549,641
<pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be :</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
267
2009-10-11T02:03:54Z
25,566,187
<p>Why do you complicate your life with joins and for loops when the solution is simple and safe??</p> <p>Just do this:</p> <pre><code>string = "the brown fox" string[0].upper()+string[1:] </code></pre>
5
2014-08-29T10:13:46Z
[ "python", "capitalization", "capitalize" ]
Regex From .NET to Python
1,549,716
<p>I have a regular expression which works perfectly well (although I am sure it is weak) in .NET/C#:</p> <pre><code>((^|\s))(?&lt;tag&gt;\@(?&lt;tagname&gt;(\w|\+)+))(?($|\s|\.)) </code></pre> <p>I am trying to move it over to Python, but I seem to be running into a formatting issue (invalid expression exception).</...
0
2009-10-11T02:58:35Z
1,549,730
<p>Is "(?" there to prevent creation of a separate group? In Python's re's, this is "(:?". Try this:</p> <pre><code>r = re.compile(r'((^|\s))(:?&lt;tag&gt;\@(:?&lt;tagname&gt;(\w|\+)+))(:?($|\s|\.))') </code></pre> <p>Also, note the use of a raw string literal (the "r" character just before the quotes). Raw litera...
-1
2009-10-11T03:03:21Z
[ "python", "regex" ]
Regex From .NET to Python
1,549,716
<p>I have a regular expression which works perfectly well (although I am sure it is weak) in .NET/C#:</p> <pre><code>((^|\s))(?&lt;tag&gt;\@(?&lt;tagname&gt;(\w|\+)+))(?($|\s|\.)) </code></pre> <p>I am trying to move it over to Python, but I seem to be running into a formatting issue (invalid expression exception).</...
0
2009-10-11T02:58:35Z
1,549,737
<p>There are some syntax incompatibilities between .NET regexps and PCRE/Python regexps :</p> <ul> <li><code>(?&lt;name&gt;...)</code> is <code>(?P&lt;name&gt;...)</code></li> <li><code>(?...)</code> does not exist, and as I don't know what it is used for in .NET I can't guess any equivalent. A Google codesearch do no...
1
2009-10-11T03:06:55Z
[ "python", "regex" ]
Difference between defining a member in __init__ to defining it in the class body in python?
1,549,722
<p>What is the difference between doing</p> <pre><code>class a: def __init__(self): self.val=1 </code></pre> <p>to doing</p> <pre><code>class a: val=1 def __init__(self): pass </code></pre>
6
2009-10-11T03:00:40Z
1,549,749
<pre><code>class a: def __init__(self): self.val=1 </code></pre> <p>this creates a class (in Py2, a cruddy, legacy, old-style, <strong>don't do that!</strong> class; in Py3, the nasty old legacy classes have finally gone away so this would be a class of the one and only kind -- the *<em>good</em> kind, which...
9
2009-10-11T03:15:07Z
[ "python", "class", "init" ]
Difference between defining a member in __init__ to defining it in the class body in python?
1,549,722
<p>What is the difference between doing</p> <pre><code>class a: def __init__(self): self.val=1 </code></pre> <p>to doing</p> <pre><code>class a: val=1 def __init__(self): pass </code></pre>
6
2009-10-11T03:00:40Z
1,550,046
<p>As mentioned by others, in one case it's an attribute on the class on the other an attribute on the instance. Does this matter? Yes, in one case it does. As Alex said, if the value is mutable. The best explanation is code, so I'll add some code to show it (that's all this answer does, really):</p> <p>First a class ...
5
2009-10-11T06:47:02Z
[ "python", "class", "init" ]
Difference between defining a member in __init__ to defining it in the class body in python?
1,549,722
<p>What is the difference between doing</p> <pre><code>class a: def __init__(self): self.val=1 </code></pre> <p>to doing</p> <pre><code>class a: val=1 def __init__(self): pass </code></pre>
6
2009-10-11T03:00:40Z
1,550,873
<p>Others have explained the technical differences. I'll try to explain why you might want to use class variables.</p> <p>If you're only instantiating the class once, then class variables effectively <em>are</em> instance variables. However, if you're making many copies, or want to share state among a few instances,...
5
2009-10-11T14:52:22Z
[ "python", "class", "init" ]
Unexpected result on a simple example
1,549,795
<pre><code># Barn yard example: counting heads and legs def solve(numLegs, numHeads): for numChicks in range(0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4*numPigs + 2*numChicks if totLegs == numLegs: return [numPigs, numChicks] return [None, None] def barnYard(heads, legs)...
0
2009-10-11T03:47:05Z
1,549,799
<p>look at your indentation. <code>return [None, None]</code> is inside the loop. it returns <code>[None, None]</code> after the first iteration</p>
3
2009-10-11T03:48:49Z
[ "python" ]
Unexpected result on a simple example
1,549,795
<pre><code># Barn yard example: counting heads and legs def solve(numLegs, numHeads): for numChicks in range(0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4*numPigs + 2*numChicks if totLegs == numLegs: return [numPigs, numChicks] return [None, None] def barnYard(heads, legs)...
0
2009-10-11T03:47:05Z
1,549,805
<p>In <code>solve()</code>, your return statement is indented to be inside of the for loop. Back it out one level, and it should work just fine.</p> <pre><code>def solve(numLegs, numHeads): for numChicks in range(0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4*numPigs + 2*numChicks ...
3
2009-10-11T03:52:29Z
[ "python" ]
Differences between isinstance() and type() in python
1,549,801
<p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p> <p>Using <code>type()</code>:</p> <pre><code>import types if type(a) is types.DictType: do_something() if type(b) in types.StringTypes: do_something_else() </code></pre> <p>Using <code>isinstance()...
588
2009-10-11T03:50:54Z
1,549,809
<p>The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because <code>isinstance()</code>'s second parameter may be a tuple:</p> <pre><code>if isinstance(b, (str, unicode)): do_something_else() </code></pre> <p>or, using the <code>basestring</c...
41
2009-10-11T03:54:17Z
[ "python", "oop", "inheritance", "types" ]
Differences between isinstance() and type() in python
1,549,801
<p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p> <p>Using <code>type()</code>:</p> <pre><code>import types if type(a) is types.DictType: do_something() if type(b) in types.StringTypes: do_something_else() </code></pre> <p>Using <code>isinstance()...
588
2009-10-11T03:50:54Z
1,549,814
<p>Here's why <code>isinstance</code> is better than <code>type</code>:</p> <pre><code>class Vehicle: pass class Truck(Vehicle): pass </code></pre> <p>in this case, a truck object is a Vehicle, but you'll get this:</p> <pre><code>isinstance(Vehicle(), Vehicle) # returns True type(Vehicle()) == Vehicle ...
149
2009-10-11T03:58:54Z
[ "python", "oop", "inheritance", "types" ]
Differences between isinstance() and type() in python
1,549,801
<p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p> <p>Using <code>type()</code>:</p> <pre><code>import types if type(a) is types.DictType: do_something() if type(b) in types.StringTypes: do_something_else() </code></pre> <p>Using <code>isinstance()...
588
2009-10-11T03:50:54Z
1,549,815
<p>According to python documentation here is a statement:</p> <blockquote> <h3><a href="http://docs.python.org/library/types.html" rel="nofollow">8.15. types — Names for built-in types</a></h3> <p>Starting in Python 2.2, built-in factory functions such as <code>int()</code> and <code>str()</code> are also...
7
2009-10-11T03:59:14Z
[ "python", "oop", "inheritance", "types" ]
Differences between isinstance() and type() in python
1,549,801
<p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p> <p>Using <code>type()</code>:</p> <pre><code>import types if type(a) is types.DictType: do_something() if type(b) in types.StringTypes: do_something_else() </code></pre> <p>Using <code>isinstance()...
588
2009-10-11T03:50:54Z
1,549,854
<p>To summarize the contents of other (already good!) answers, <code>isinstance</code> caters for inheritance (an instance of a derived class <em>is an</em> instance of a base class, too), while checking for equality of <code>type</code> does not (it demands identity of types and rejects instances of subtypes, AKA subc...
654
2009-10-11T04:31:57Z
[ "python", "oop", "inheritance", "types" ]
Differences between isinstance() and type() in python
1,549,801
<p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p> <p>Using <code>type()</code>:</p> <pre><code>import types if type(a) is types.DictType: do_something() if type(b) in types.StringTypes: do_something_else() </code></pre> <p>Using <code>isinstance()...
588
2009-10-11T03:50:54Z
28,358,473
<blockquote> <h1>Differences between <code>isinstance()</code> and <code>type()</code> in Python?</h1> </blockquote> <p>Type-checking with </p> <pre><code>isinstance(obj, Base) </code></pre> <p>allows for instances of subclasses and multiple possible bases: </p> <pre><code>isinstance(obj, (Base1, Base2)) </code><...
24
2015-02-06T04:13:45Z
[ "python", "oop", "inheritance", "types" ]
"Cloning" row or column vectors
1,550,130
<p>Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as</p> <pre><code>[1,2,3] </code></pre> <p>Into a matrix</p> <pre><code>[[1,2,3] [1,2,3] [1,2,3] ] </code></pre> <p>or a column vector such as</p> <pre><code>[1 2 3 ] </code></pre> <p>into</...
55
2009-10-11T07:54:05Z
1,550,137
<p>Here's an elegant, Pythonic way to do it:</p> <pre><code>&gt;&gt;&gt; array([[1,2,3],]*3) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) &gt;&gt;&gt; array([[1,2,3],]*3).transpose() array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) </code></pre> <p>the problem with <code>[16]</code> seems to be that ...
25
2009-10-11T07:59:23Z
[ "python", "matlab", "numpy", "octave", "linear-algebra" ]
"Cloning" row or column vectors
1,550,130
<p>Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as</p> <pre><code>[1,2,3] </code></pre> <p>Into a matrix</p> <pre><code>[[1,2,3] [1,2,3] [1,2,3] ] </code></pre> <p>or a column vector such as</p> <pre><code>[1 2 3 ] </code></pre> <p>into</...
55
2009-10-11T07:54:05Z
1,552,016
<p>First note that with numpy's <em>broadcasting</em> operations it's usually not necessary to duplicate rows and columns. See <a href="http://www.scipy.org/EricsBroadcastingDoc">this</a> and <a href="http://www.oreillynet.com/pub/a/python/2000/09/27/numerically.html?page=1">this</a> for descriptions.</p> <p>But to d...
18
2009-10-11T22:56:20Z
[ "python", "matlab", "numpy", "octave", "linear-algebra" ]
"Cloning" row or column vectors
1,550,130
<p>Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as</p> <pre><code>[1,2,3] </code></pre> <p>Into a matrix</p> <pre><code>[[1,2,3] [1,2,3] [1,2,3] ] </code></pre> <p>or a column vector such as</p> <pre><code>[1 2 3 ] </code></pre> <p>into</...
55
2009-10-11T07:54:05Z
1,582,742
<p>Use <code>numpy.tile</code>:</p> <pre><code>&gt;&gt;&gt; tile(array([1,2,3]), (3, 1)) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) </code></pre> <p>or for repeating columns:</p> <pre><code>&gt;&gt;&gt; tile(array([[1,2,3]]).transpose(), (1, 3)) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) </co...
130
2009-10-17T17:33:21Z
[ "python", "matlab", "numpy", "octave", "linear-algebra" ]
"Cloning" row or column vectors
1,550,130
<p>Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as</p> <pre><code>[1,2,3] </code></pre> <p>Into a matrix</p> <pre><code>[[1,2,3] [1,2,3] [1,2,3] ] </code></pre> <p>or a column vector such as</p> <pre><code>[1 2 3 ] </code></pre> <p>into</...
55
2009-10-11T07:54:05Z
21,146,167
<p>I think using the broadcast in numpy is the best, and faster</p> <p>I did a compare as following</p> <pre><code>import numpy as np b = np.random.randn(1000) In [105]: %timeit c = np.tile(b[:, newaxis], (1,100)) 1000 loops, best of 3: 354 µs per loop In [106]: %timeit c = np.repeat(b[:, newaxis], 100, axis=1) 100...
4
2014-01-15T19:10:59Z
[ "python", "matlab", "numpy", "octave", "linear-algebra" ]
Problem about python writing files
1,550,132
<p>I've got a weird problem with python programming. I used the statement'writelines()' to write a series of lists into a new file.During the process I could see the context in the file icon via preview, however once after the program finished running the output file comes out to be a blank file.</p> <p>In short, my p...
0
2009-10-11T07:54:44Z
1,550,166
<p>I guess it's caused by incorrect indentation. The <code>break</code> statement should be inside the <code>if</code> block. The loop as it is written will only try the first option from <code>judge</code>. Check if you don't have mixed spaces and tabs in the file.</p>
2
2009-10-11T08:14:54Z
[ "python", "file" ]
How to assign a variable in IF, and then return it. (Python)
1,550,134
<pre><code>def isBig(x): if x &gt; 4: return 'apple' else: return 'orange' </code></pre> <p>This works:</p> <pre><code>if isBig(y): return isBig(y) </code></pre> <p>This does NOT work:</p> <pre><code>if fruit = isBig(y): return fruit </code></pre> <p>Why doesn't the 2nd one work!? I want a 1-...
7
2009-10-11T07:57:29Z
1,550,142
<p>This doesn't work due to intentional language design, but you can use <a href="http://code.activestate.com/recipes/66061/" rel="nofollow">this trick</a> to get around this decision</p>
0
2009-10-11T08:01:39Z
[ "python" ]
How to assign a variable in IF, and then return it. (Python)
1,550,134
<pre><code>def isBig(x): if x &gt; 4: return 'apple' else: return 'orange' </code></pre> <p>This works:</p> <pre><code>if isBig(y): return isBig(y) </code></pre> <p>This does NOT work:</p> <pre><code>if fruit = isBig(y): return fruit </code></pre> <p>Why doesn't the 2nd one work!? I want a 1-...
7
2009-10-11T07:57:29Z
1,550,145
<p>The problem is that the assignment operation cannot be evaluated as having a boolean value. The <code>if</code> statement relies on being able to evaluate a boolean. For example,</p> <pre><code>&gt;&gt;&gt; fruit = 'apple' &gt;&gt;&gt; bool(fruit = 'apple') ----------------------------------------------------------...
0
2009-10-11T08:02:37Z
[ "python" ]
How to assign a variable in IF, and then return it. (Python)
1,550,134
<pre><code>def isBig(x): if x &gt; 4: return 'apple' else: return 'orange' </code></pre> <p>This works:</p> <pre><code>if isBig(y): return isBig(y) </code></pre> <p>This does NOT work:</p> <pre><code>if fruit = isBig(y): return fruit </code></pre> <p>Why doesn't the 2nd one work!? I want a 1-...
7
2009-10-11T07:57:29Z
1,550,147
<p>If you want to code in PHP (or C), code in it. Don't try to force its methods onto another language.</p> <p>One of the basic tenets behind Python (in my opinion) is its readability. You should be using:</p> <pre><code>fruit = isBig(y) if fruit: return fruit </code></pre> <p>I should also mention that your use of ...
3
2009-10-11T08:03:19Z
[ "python" ]
How to assign a variable in IF, and then return it. (Python)
1,550,134
<pre><code>def isBig(x): if x &gt; 4: return 'apple' else: return 'orange' </code></pre> <p>This works:</p> <pre><code>if isBig(y): return isBig(y) </code></pre> <p>This does NOT work:</p> <pre><code>if fruit = isBig(y): return fruit </code></pre> <p>Why doesn't the 2nd one work!? I want a 1-...
7
2009-10-11T07:57:29Z
1,550,148
<p>The one liner doesn't work because, in Python, assignment (<code>fruit = isBig(y)</code>) is a statement, not an expression. In C, C++, Perl, and countless other languages it is an expression, and you can put it in an <code>if</code> or a <code>while</code> or whatever you like, but not in Python, because the creato...
8
2009-10-11T08:03:25Z
[ "python" ]
How to assign a variable in IF, and then return it. (Python)
1,550,134
<pre><code>def isBig(x): if x &gt; 4: return 'apple' else: return 'orange' </code></pre> <p>This works:</p> <pre><code>if isBig(y): return isBig(y) </code></pre> <p>This does NOT work:</p> <pre><code>if fruit = isBig(y): return fruit </code></pre> <p>Why doesn't the 2nd one work!? I want a 1-...
7
2009-10-11T07:57:29Z
1,551,223
<p>I see somebody else has already pointed to my old "assign and set" Cookbook recipe, which boils down in its simplest version to:</p> <pre><code>class Holder(object): def set(self, value): self.value = value return value def get(self): return self.value h = Holder() ... if h.set(isBig(y)): re...
14
2009-10-11T17:31:16Z
[ "python" ]
How to assign a variable in IF, and then return it. (Python)
1,550,134
<pre><code>def isBig(x): if x &gt; 4: return 'apple' else: return 'orange' </code></pre> <p>This works:</p> <pre><code>if isBig(y): return isBig(y) </code></pre> <p>This does NOT work:</p> <pre><code>if fruit = isBig(y): return fruit </code></pre> <p>Why doesn't the 2nd one work!? I want a 1-...
7
2009-10-11T07:57:29Z
19,688,351
<pre><code>print "apple" if x &gt; 4 else "orange" </code></pre>
0
2013-10-30T16:22:20Z
[ "python" ]
Why doesn't memcache work in my Django?
1,550,180
<pre><code>from django.core.cache import cache def testcache(): cache.set('test','I am putting this message in',3333) print cache.get('test') </code></pre> <p>It just prints "<strong>None</strong>"</p> <p>This is in "ps aux":</p> <pre><code>dovr 2241 0.0 0.8 57824 2144 ? Ssl 04:2...
1
2009-10-11T08:25:24Z
1,550,488
<p>You can insure that you can reach memcached from your code by logging value returned from <code>set()</code> method. Probably memcached listens on 127.0.0.1 while you are trying to connect to external interface.</p>
2
2009-10-11T11:33:00Z
[ "python", "django", "memcached" ]
Why doesn't memcache work in my Django?
1,550,180
<pre><code>from django.core.cache import cache def testcache(): cache.set('test','I am putting this message in',3333) print cache.get('test') </code></pre> <p>It just prints "<strong>None</strong>"</p> <p>This is in "ps aux":</p> <pre><code>dovr 2241 0.0 0.8 57824 2144 ? Ssl 04:2...
1
2009-10-11T08:25:24Z
1,552,188
<p>Solved.</p> <p>Django was talking to the server. I did "nc IPADRESS 11211" . And typed "stats"</p> <p>Then, I looked that cmd_get and cmd_set were changing, so that means it's talking.</p> <p>Then, I realized that I had problem with code in my views. You can't have "space" in the key. It has to be non-spaceless (...
0
2009-10-12T00:20:41Z
[ "python", "django", "memcached" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
1,550,235
<p>You need to remove all files manually, and also undo any other stuff that installation did manually.</p> <p>If you don't know the list of all files, you can reinstall it with the <code>--record</code> option, and take a look at the list this produces.</p> <p>To record list of installed files, you can use:</p> <pr...
621
2009-10-11T09:12:27Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
1,550,237
<p>Go to your python package directory and remove your .egg file, e.g.: In python 2.5(ubuntu): /usr/lib/python2.5/site-packages/</p> <p>In python 2.6(ubuntu): /usr/local/lib/python2.6/dist-packages/</p>
4
2009-10-11T09:13:35Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
1,550,238
<p>The lazy way: simply uninstall from the Windows installation menu (if you're using Windows), or from the rpm command, provided you first re-install it after creating a distribution package.</p> <p>For example,</p> <pre><code>python setup.py bdist_wininst dist/foo-1.0.win32.exe </code></pre> <p>("foo" being an exa...
7
2009-10-11T09:13:42Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
1,868,741
<p>Extending on what Martin said, recording the install output and a little bash scripting does the trick quite nicely. Here's what I do...</p> <pre><code>for i in $(less install.record); sudo rm $i; done; </code></pre> <p>And presto. Uninstalled.</p>
1
2009-12-08T18:00:04Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
4,042,668
<p>Or more simply you could just do;</p> <pre><code>sudo rm $(cat install.record) </code></pre> <p>This works because the rm command takes a whitespace-seperated list of files to delete and your installation record is just such a list. Also, using "less" for this type of command could get you in big trouble dependin...
21
2010-10-28T12:00:21Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
12,797,865
<p>For me, the following mostly works:</p> <p>have pip installed, e.g.:</p> <pre><code>$ easy_install pip </code></pre> <p>Check, how is your installed package named from pip point of view:</p> <pre><code>$ pip freeze </code></pre> <p>This shall list names of all packages, you have installed (and which were detect...
164
2012-10-09T10:19:27Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
20,719,865
<p>It might be better to remove related files by using bash to read commands, like the following:</p> <pre><code>sudo python setup.py install --record files.txt sudo bash -c "cat files.txt | xargs rm -rf" </code></pre>
0
2013-12-21T14:13:28Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
20,780,379
<p>Probably you can do this as an alternative :-</p> <p>1) Get the python version -</p> <pre><code>[linux machine]# python Python 2.4.3 (#1, Jun 18 2012, 14:38:55) </code></pre> <p>-> The above command gives you the current python Version which is <strong>2.4.3</strong></p> <p>2) Get the installation directory of ...
3
2013-12-26T06:44:14Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
25,209,129
<p>The #1 answer has problems:</p> <ul> <li>Won't work on mac.</li> <li>If a file is installed which includes spaces or other special characters, the xargs command will fail, and delete any files/directories which matched the individual words.</li> <li>the -r in rm -rf is unnecessary and at worst could delete things y...
50
2014-08-08T17:34:59Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
32,382,242
<p>Now python gives you the choice to install <code>pip</code> during the installation (I am on Windows, and at least python does so for Windows!). Considering you had chosen to install <code>pip</code> during installation of python (you don't actually have to choose because it is default), <code>pip</code> is already ...
4
2015-09-03T17:44:44Z
[ "python", "setup.py", "pypi" ]
python setup.py uninstall
1,550,226
<p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
489
2009-10-11T09:06:56Z
33,326,037
<p>I think you can open the setup.py, locate the package name, and then ask pip to uninstall it.</p> <p>Assuming the name is available in a 'METADATA' variable:</p> <pre><code>pip uninstall $(python -c "from setup import METADATA; print METADATA['name']") </code></pre>
3
2015-10-25T03:57:02Z
[ "python", "setup.py", "pypi" ]
Counting all the keys pressed and what they are (python)
1,550,273
<p>I'd like to create a map of the number of presses for every key for a project I'm working on.</p> <p>I'd like to do this with a Python module. Is it possible to do this in any way?</p>
0
2009-10-11T09:34:38Z
1,550,298
<p>On Windows, a possible solution is to install <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">Python for Windows extensions</a> and use the <a href="http://docs.activestate.com/activepython/2.4/pywin32/PyCWnd%5F%5FHookAllKeyStrokes%5Fmeth.html" rel="nofollow">PyCWnd.HookAllKeyStrokes</a></p>
1
2009-10-11T09:50:21Z
[ "python", "key", "counting" ]
Counting all the keys pressed and what they are (python)
1,550,273
<p>I'd like to create a map of the number of presses for every key for a project I'm working on.</p> <p>I'd like to do this with a Python module. Is it possible to do this in any way?</p>
0
2009-10-11T09:34:38Z
1,550,656
<p>As Nick D <a href="http://stackoverflow.com/questions/1550273/counting-all-the-keys-pressed-and-what-they-are-python/1550298#1550298">points out</a>, on Windows, the <a href="http://pypi.python.org/pypi/pyHook/1.4/" rel="nofollow">PyHook library</a> would work.</p> <p>On Linux, the <a href="http://python-xlib.sourc...
1
2009-10-11T13:10:37Z
[ "python", "key", "counting" ]
web2py - how to inject html
1,550,368
<p>i used rows.xml() to generate html output. i want to know how to add html codes to this generated html page e.g: "add logo, link css file,.. etc"</p> <p><code>rows=db(db.member.membership_id==request.args[0]).select(db.member.membership_id ,db.member.first_name,db.m...
2
2009-10-11T10:32:08Z
1,550,391
<p>Just prepend/append it to the string that <code>rows.xml()</code> returns:</p> <pre><code>html = '&lt;html&gt;&lt;head&gt;...&lt;/head&gt;&lt;body&gt;' + rows.xml() + '&lt;/body&gt;&lt;/html&gt;' </code></pre>
0
2009-10-11T10:44:45Z
[ "python", "web2py" ]
web2py - how to inject html
1,550,368
<p>i used rows.xml() to generate html output. i want to know how to add html codes to this generated html page e.g: "add logo, link css file,.. etc"</p> <p><code>rows=db(db.member.membership_id==request.args[0]).select(db.member.membership_id ,db.member.first_name,db.m...
2
2009-10-11T10:32:08Z
1,550,413
<p>There are many HTML helpers you can use, for example:</p> <pre><code>html_code = A('&lt;click&gt;', rows.xml(), _href='http://mylink') html_code = B('Results:', rows.xml(), _class='results', _id=1) html_page = HTML(BODY(B('Results:', rows.xml(), _class='results', _id=1))) </code></pre> <p>and so on.</p> <p>You ca...
2
2009-10-11T10:56:26Z
[ "python", "web2py" ]
I do urllib2 and I download the htmlSource of the webpage. How do I make this all on 1 line?
1,550,406
<pre><code>urlReq = urllib2.Request(theurl) urlReq.add_header('User-Agent',random.choice(agents)) urlResponse = urllib2.urlopen(urlReq) htmlSource = urlResponse.read() </code></pre> <p>How do I make htmlSource in 1 line, instead of many lines?</p>
-5
2009-10-11T10:50:04Z
1,550,414
<p>You can't really do that, the only possible thing is put the response and the source on the same line. Or you could use <code>;</code> between statements, but that's ugly.</p> <p>But more importantly, why would you do that? Why is it better to have it all in on line?</p> <pre><code>&gt;&gt;&gt; import this The Ze...
9
2009-10-11T10:56:59Z
[ "python" ]
I do urllib2 and I download the htmlSource of the webpage. How do I make this all on 1 line?
1,550,406
<pre><code>urlReq = urllib2.Request(theurl) urlReq.add_header('User-Agent',random.choice(agents)) urlResponse = urllib2.urlopen(urlReq) htmlSource = urlResponse.read() </code></pre> <p>How do I make htmlSource in 1 line, instead of many lines?</p>
-5
2009-10-11T10:50:04Z
1,550,436
<p>How to do that in one line? That's what functions are for. Like this:</p> <pre><code>def getsource(url): urlReq = urllib2.Request(url) urlReq.add_header('User-Agent',random.choice(agents)) urlResponse = urllib2.urlopen(urlReq) return urlResponse.read() </code></pre> <p>Now you can do it in one line...
6
2009-10-11T11:06:50Z
[ "python" ]
Python: is using "..%(var)s.." % locals() a good practice?
1,550,479
<p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p> <p>I feel it is very agile:</p> <pre><code>def example(): age = ... name = ... print "hello %(name)s you are %(age)s years old" % locals() </code></pre> <p>Sometimes I use its cousin:</p> <pre><code>def example2(obj): pr...
65
2009-10-11T11:27:38Z
1,550,483
<p>I think it is a great pattern because you are leveraging built-in functionality to reduce the code you need to write. I personally find it quite Pythonic.</p> <p>I never write code that I don't need to write - less code is better than more code and this practice of using <code>locals()</code> for example allows me...
8
2009-10-11T11:28:56Z
[ "python", "string", "design-patterns", "anti-patterns" ]
Python: is using "..%(var)s.." % locals() a good practice?
1,550,479
<p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p> <p>I feel it is very agile:</p> <pre><code>def example(): age = ... name = ... print "hello %(name)s you are %(age)s years old" % locals() </code></pre> <p>Sometimes I use its cousin:</p> <pre><code>def example2(obj): pr...
65
2009-10-11T11:27:38Z
1,550,527
<p>The <code>"%(name)s" % &lt;dictionary&gt;</code> or even better, the <code>"{name}".format(&lt;parameters&gt;)</code> have the merit of </p> <ul> <li>being more readable than "%0s"</li> <li>being independent from the argument order</li> <li>not compelling to use all the arguments in the string</li> </ul> <p>I woul...
8
2009-10-11T11:54:55Z
[ "python", "string", "design-patterns", "anti-patterns" ]
Python: is using "..%(var)s.." % locals() a good practice?
1,550,479
<p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p> <p>I feel it is very agile:</p> <pre><code>def example(): age = ... name = ... print "hello %(name)s you are %(age)s years old" % locals() </code></pre> <p>Sometimes I use its cousin:</p> <pre><code>def example2(obj): pr...
65
2009-10-11T11:27:38Z
1,550,665
<p>Using the built-in <code>vars([object])</code> (<a href="http://docs.python.org/3.1/library/functions.html#vars">documentation</a>) might make the second look better to you:</p> <pre><code>def example2(obj): print "The file at %(path)s has %(length)s bytes" % vars(obj) </code></pre> <p>The effect is of course ...
6
2009-10-11T13:15:38Z
[ "python", "string", "design-patterns", "anti-patterns" ]
Python: is using "..%(var)s.." % locals() a good practice?
1,550,479
<p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p> <p>I feel it is very agile:</p> <pre><code>def example(): age = ... name = ... print "hello %(name)s you are %(age)s years old" % locals() </code></pre> <p>Sometimes I use its cousin:</p> <pre><code>def example2(obj): pr...
65
2009-10-11T11:27:38Z
1,550,684
<p>Never in a million years. It's unclear what the context for formatting is: <code>locals</code> could include almost any variable. <code>self.__dict__</code> is not as vague. Perfectly awful to leave future developers scratching their heads over what's local and what's not local.</p> <p>It's an intentional myster...
11
2009-10-11T13:22:53Z
[ "python", "string", "design-patterns", "anti-patterns" ]
Python: is using "..%(var)s.." % locals() a good practice?
1,550,479
<p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p> <p>I feel it is very agile:</p> <pre><code>def example(): age = ... name = ... print "hello %(name)s you are %(age)s years old" % locals() </code></pre> <p>Sometimes I use its cousin:</p> <pre><code>def example2(obj): pr...
65
2009-10-11T11:27:38Z
1,551,187
<p>It's OK for small applications and allegedly "one-off" scripts, especially with the <code>vars</code> enhancement mentioned by @kaizer.se and the <code>.format</code> version mentioned by @RedGlyph. </p> <p>However, for large applications with a long maintenance life and many maintainers this practice can lead to m...
80
2009-10-11T17:14:09Z
[ "python", "string", "design-patterns", "anti-patterns" ]
Python: is using "..%(var)s.." % locals() a good practice?
1,550,479
<p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p> <p>I feel it is very agile:</p> <pre><code>def example(): age = ... name = ... print "hello %(name)s you are %(age)s years old" % locals() </code></pre> <p>Sometimes I use its cousin:</p> <pre><code>def example2(obj): pr...
65
2009-10-11T11:27:38Z
6,106,580
<p>Regarding the "cousin", instead of <code>obj.__dict__</code>, it looks a lot better with new string formatting:</p> <pre><code>def example2(obj): print "The file at {o.path} has {o.length} bytes".format(o=obj) </code></pre> <p>I use this a lot for <strong>repr</strong> methods, e.g.</p> <pre><code>def __repr_...
8
2011-05-24T06:32:44Z
[ "python", "string", "design-patterns", "anti-patterns" ]