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: Get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition) | 2,403,372 | <p>I have a python dictionary whose keys are strings and the values are objects.</p>
<p>For instance, and object with one string and one int</p>
<pre><code>class DictItem:
def __init__(self, field1, field2):
self.field1 = str(field1)
self.field2 = int(field2)
</code></pre>
<p>and the dictionary:</p>
... | 5 | 2010-03-08T17:46:38Z | 2,403,568 | <p><em>The idea is creating a "sub-dictionary" (a list would do too)</em></p>
<p>If you want a list you could use <a href="http://docs.python.org/library/functions.html#filter" rel="nofollow">filter</a> (or <a href="http://docs.python.org/library/itertools.html#itertools.ifilter" rel="nofollow">itertools.ifilter</a>):... | 2 | 2010-03-08T18:11:26Z | [
"python",
"dictionary"
] |
Python: Get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition) | 2,403,372 | <p>I have a python dictionary whose keys are strings and the values are objects.</p>
<p>For instance, and object with one string and one int</p>
<pre><code>class DictItem:
def __init__(self, field1, field2):
self.field1 = str(field1)
self.field2 = int(field2)
</code></pre>
<p>and the dictionary:</p>
... | 5 | 2010-03-08T17:46:38Z | 2,403,575 | <p>'Most efficient' is going to depend on how often the dictionary contents change compared to how often you are doing the lookup.</p>
<p>If the dictionary changes often and you do the lookup less often then the most efficient method will be walking through iteritems and selecting the objects that match the criteria, ... | 0 | 2010-03-08T18:12:17Z | [
"python",
"dictionary"
] |
Python: Get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition) | 2,403,372 | <p>I have a python dictionary whose keys are strings and the values are objects.</p>
<p>For instance, and object with one string and one int</p>
<pre><code>class DictItem:
def __init__(self, field1, field2):
self.field1 = str(field1)
self.field2 = int(field2)
</code></pre>
<p>and the dictionary:</p>
... | 5 | 2010-03-08T17:46:38Z | 2,403,724 | <p>To make a <code>dict</code> from your <code>dict</code>,</p>
<pre><code>subdict = dict((k, v) for k, v in myDict.iteritems() if v.field2 >= 2)
</code></pre>
| 6 | 2010-03-08T18:31:18Z | [
"python",
"dictionary"
] |
fastest calculation of largest prime factor of 512 bit number in python | 2,403,578 | <p>i am simulating my crypto scheme in python, i am a new user to it.</p>
<p>p = 512 bit number and i need to calculate largest prime factor for it, i am looking for two things:</p>
<ol>
<li>Fastest code to process this large prime factorization</li>
<li>Code that can take 512 bit of number as input and can handle it... | 1 | 2010-03-08T18:12:27Z | 2,403,706 | <p>If you can install an extension, <a href="http://code.google.com/p/gmpy/" rel="nofollow">gmpy</a> would help -- see my answer to this <a href="http://stackoverflow.com/questions/1019040/how-many-numbers-below-n-are-coprimes-to-n">SO question</a>, specifically the <code>def prime_factors(x)</code> function in the cod... | 1 | 2010-03-08T18:29:01Z | [
"python",
"primes",
"factorization"
] |
fastest calculation of largest prime factor of 512 bit number in python | 2,403,578 | <p>i am simulating my crypto scheme in python, i am a new user to it.</p>
<p>p = 512 bit number and i need to calculate largest prime factor for it, i am looking for two things:</p>
<ol>
<li>Fastest code to process this large prime factorization</li>
<li>Code that can take 512 bit of number as input and can handle it... | 1 | 2010-03-08T18:12:27Z | 2,403,810 | <p>This should be a better fit then the trivial approach for large numbers (although with this kind of number crunching every pure Python implementation will take a while): <a href="http://code.activestate.com/recipes/577037-pollard-rho-prime-factorization/" rel="nofollow">Pollard Rho prime factorization</a>.</p>
| 1 | 2010-03-08T18:47:45Z | [
"python",
"primes",
"factorization"
] |
fastest calculation of largest prime factor of 512 bit number in python | 2,403,578 | <p>i am simulating my crypto scheme in python, i am a new user to it.</p>
<p>p = 512 bit number and i need to calculate largest prime factor for it, i am looking for two things:</p>
<ol>
<li>Fastest code to process this large prime factorization</li>
<li>Code that can take 512 bit of number as input and can handle it... | 1 | 2010-03-08T18:12:27Z | 2,404,066 | <pre><code>('''==============================================================================='''
> ''' CALCULATE HIGHEST PRIME
> FACTOR '''
>
> '''===============================================================================''')
>
> #!/usr/bin/e... | 0 | 2010-03-08T19:24:36Z | [
"python",
"primes",
"factorization"
] |
fastest calculation of largest prime factor of 512 bit number in python | 2,403,578 | <p>i am simulating my crypto scheme in python, i am a new user to it.</p>
<p>p = 512 bit number and i need to calculate largest prime factor for it, i am looking for two things:</p>
<ol>
<li>Fastest code to process this large prime factorization</li>
<li>Code that can take 512 bit of number as input and can handle it... | 1 | 2010-03-08T18:12:27Z | 2,407,085 | <p>For a Python-based solution, you might want to look at <a href="http://sourceforge.net/projects/pyecm/" rel="nofollow">pyecm</a> On a system with gmpy installed also, pyecm found the following factors:</p>
<p>101, 521, 3121, 9901, 36479, 300623, 53397071018461, 1900381976777332243781</p>
<p>There still is a 98 dig... | 3 | 2010-03-09T06:36:46Z | [
"python",
"primes",
"factorization"
] |
How do I watch a folder for changes and when changes are done using Python? | 2,404,087 | <p>i need to watch a folder for incoming files. i did that with the following help:<br>
<a href="http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python">http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python</a><br>
the problem is that the files that a... | 0 | 2010-03-08T19:28:10Z | 2,404,310 | <p>If you have control over the process of importing the files, I would put a lock file when starting to copy files in, and remove it when you are done. by lock file I mean a tmp empty file, which is just there to indicate that you are coping a file. then your py script can check for the existence of the lock files.</p... | 0 | 2010-03-08T20:02:08Z | [
"python",
"monitoring",
"pywin32",
"watch"
] |
How do I watch a folder for changes and when changes are done using Python? | 2,404,087 | <p>i need to watch a folder for incoming files. i did that with the following help:<br>
<a href="http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python">http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python</a><br>
the problem is that the files that a... | 0 | 2010-03-08T19:28:10Z | 2,404,688 | <p>You may be able to use <code>os.stat()</code> to monitor the mtime of the file. However be aware that under various network conditions, the copy may stall momentarily and so the mtime is not updated for a few seconds, so you need to make allowance for this.</p>
<p>Another option is to try opening the file with excl... | 0 | 2010-03-08T20:58:38Z | [
"python",
"monitoring",
"pywin32",
"watch"
] |
How do I watch a folder for changes and when changes are done using Python? | 2,404,087 | <p>i need to watch a folder for incoming files. i did that with the following help:<br>
<a href="http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python">http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python</a><br>
the problem is that the files that a... | 0 | 2010-03-08T19:28:10Z | 2,404,711 | <p>The most reliable method would be to write your own program to move the files.</p>
| 0 | 2010-03-08T21:03:25Z | [
"python",
"monitoring",
"pywin32",
"watch"
] |
How do I watch a folder for changes and when changes are done using Python? | 2,404,087 | <p>i need to watch a folder for incoming files. i did that with the following help:<br>
<a href="http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python">http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python</a><br>
the problem is that the files that a... | 0 | 2010-03-08T19:28:10Z | 2,404,848 | <p>try checking for the last-modified time change instead of the filesize during your poll.</p>
| 0 | 2010-03-08T21:21:29Z | [
"python",
"monitoring",
"pywin32",
"watch"
] |
How do I watch a folder for changes and when changes are done using Python? | 2,404,087 | <p>i need to watch a folder for incoming files. i did that with the following help:<br>
<a href="http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python">http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python</a><br>
the problem is that the files that a... | 0 | 2010-03-08T19:28:10Z | 2,404,883 | <p>You should take a look at this link:</p>
<p><a href="http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html" rel="nofollow">http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html</a></p>
<p>There you can see the comparison of the method you are speaking about (simple p... | 1 | 2010-03-08T21:26:36Z | [
"python",
"monitoring",
"pywin32",
"watch"
] |
Applying style sheets in pyqt | 2,404,317 | <p>If i apply a property to a parent widget it is automatically applied for child widgets too.. Is there any way of preventing this?? For example if i set background color as white in a dialog the button,combo boxes and scroll bars looks white as it lacks it native look(have to say it's unpleasant & ugly).. Is ther... | 4 | 2010-03-08T20:03:07Z | 2,418,726 | <p>Found a solution..</p>
<p>Instead of using </p>
<pre><code>self.groupBox.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border:1px solid rgb(255, 170, 255);")
</code></pre>
<p>use specifically using selector types..</p>
<pre><code>self.groupBox.setStyleSheet("QGroupB... | 9 | 2010-03-10T16:43:54Z | [
"python",
"qt4",
"pyqt",
"stylesheet",
"pyqt4"
] |
Does filehandle get closed automatically in Python after it goes out of scope? | 2,404,430 | <p>If I do the following, does filehandle get closed automatically as it goes out of scope in Python:</p>
<pre><code>def read_contents(file_path):
return file(file_path).read()
</code></pre>
<p>If it doesn't, how can I write this function to close the scope automatically?</p>
| 17 | 2010-03-08T20:18:51Z | 2,404,471 | <p>It should close the file handle in the file's <code>__del__</code> statement, but a better approach would be to use a <code>with</code> block:</p>
<pre><code>def read_contents(file_path):
with open(file_path, 'r') as f:
return f.read()
</code></pre>
<p>See <a href="http://docs.python.org/library/stdtypes.htm... | 17 | 2010-03-08T20:23:18Z | [
"python",
"file",
"scope"
] |
Does filehandle get closed automatically in Python after it goes out of scope? | 2,404,430 | <p>If I do the following, does filehandle get closed automatically as it goes out of scope in Python:</p>
<pre><code>def read_contents(file_path):
return file(file_path).read()
</code></pre>
<p>If it doesn't, how can I write this function to close the scope automatically?</p>
| 17 | 2010-03-08T20:18:51Z | 2,404,671 | <p>To expand on FogleBird's answer, if you do not explicitly close it then the file will be closed automatically when the file object is destroyed. In CPython this will happen as soon as there are no more references to it, e.g. if it is a local variable in a function and the function ends. However if an exception is ... | 23 | 2010-03-08T20:55:52Z | [
"python",
"file",
"scope"
] |
Vectorization of index operation for a scipy.sparse matrix | 2,404,437 | <p>The following code runs too slowly even though everything seems to be vectorized. </p>
<pre><code>from numpy import *
from scipy.sparse import *
n = 100000;
i = xrange(n); j = xrange(n);
data = ones(n);
A=csr_matrix((data,(i,j)));
x = A[i,j]
</code></pre>
<p>The problem seems to be that the indexing operation i... | 6 | 2010-03-08T20:19:50Z | 2,404,797 | <p>You can use <code>A.diagonal()</code> to retrieve the diagonal much more quickly (0.0009 seconds vs. 3.8 seconds on my machine) . However, if you want to do arbitary indexing then that is a more complicated question because you aren't using slices so much as a list of indices. The _get_single_element function is bei... | 7 | 2010-03-08T21:14:23Z | [
"python",
"indexing",
"scipy",
"sparse-matrix"
] |
Vectorization of index operation for a scipy.sparse matrix | 2,404,437 | <p>The following code runs too slowly even though everything seems to be vectorized. </p>
<pre><code>from numpy import *
from scipy.sparse import *
n = 100000;
i = xrange(n); j = xrange(n);
data = ones(n);
A=csr_matrix((data,(i,j)));
x = A[i,j]
</code></pre>
<p>The problem seems to be that the indexing operation i... | 6 | 2010-03-08T20:19:50Z | 2,404,906 | <p>I think _get_single_element is only called when the default dtype of 'object' is used. Have you tried providing a dtype, such as <code>csr_matrix((data, (i,j)), dtype=int32)</code></p>
| 0 | 2010-03-08T21:30:17Z | [
"python",
"indexing",
"scipy",
"sparse-matrix"
] |
Macport Python with PyObj and XCode | 2,404,505 | <p>How can I get the Macport Python version to work with XCode? Which Python.framework do I have to choose?</p>
| 1 | 2010-03-08T20:28:25Z | 6,135,411 | <p>Perhaps take a look here: < <a href="http://superuser.com/questions/35256/how-can-i-change-the-default-python-version-on-snow-leopard">http://superuser.com/questions/35256/how-can-i-change-the-default-python-version-on-snow-leopard</a> >. The final solution mentions using python_select. Assuming you install diffe... | 1 | 2011-05-26T07:57:38Z | [
"python",
"xcode",
"pyobjc"
] |
How can I turn off registry redirection on Python? | 2,404,595 | <p>My program is trying to create an key on the</p>
<pre><code>HKLM\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
</code></pre>
<p>but instead the key is created on the</p>
<pre><code>HKLM\Wow6432node\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
</code></pre>
<p>and don't work properly... W... | 1 | 2010-03-08T20:44:38Z | 2,405,490 | <p>You can use:</p>
<pre><code>import _winreg
_winreg.DisableReflectionKey(_winreg.HKEY_LOCAL_MACHINE)
# do stuff here
_winreg.EnableReflectionKey(_winreg.HKEY_LOCAL_MACHINE)
</code></pre>
<p>This only works in Python 2.6 and above however.</p>
| 0 | 2010-03-08T23:05:20Z | [
"python",
"windows",
"registry",
"64bit"
] |
How can I turn off registry redirection on Python? | 2,404,595 | <p>My program is trying to create an key on the</p>
<pre><code>HKLM\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
</code></pre>
<p>but instead the key is created on the</p>
<pre><code>HKLM\Wow6432node\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
</code></pre>
<p>and don't work properly... W... | 1 | 2010-03-08T20:44:38Z | 2,406,321 | <p>The docs on reflection-key features in winreg are scarce (and bits and pieces are missing). You really need <a href="http://bugs.python.org/issue7347" rel="nofollow">this patch</a>, but until it's applied and a new micro-release of Python is made with these fixes, at least you can try the <code>DisableReflectionKey... | 2 | 2010-03-09T02:42:55Z | [
"python",
"windows",
"registry",
"64bit"
] |
Fastest way to convert file from latin1 to utf-8 in python | 2,404,855 | <p>I need fastest way to convert files from latin1 to utf-8 in python. The files are large ~ 2G. ( I am moving DB data ). So far I have</p>
<pre><code>import codecs
infile = codecs.open(tmpfile, 'r', encoding='latin1')
outfile = codecs.open(tmpfile1, 'w', encoding='utf-8')
for line in infile:
outfile.write(line)
... | 4 | 2010-03-08T21:22:24Z | 2,404,870 | <p>I would go with <a href="http://www.gnu.org/software/libiconv/documentation/libiconv/iconv.1.html">iconv</a> and a system call.</p>
| 6 | 2010-03-08T21:24:32Z | [
"python"
] |
Fastest way to convert file from latin1 to utf-8 in python | 2,404,855 | <p>I need fastest way to convert files from latin1 to utf-8 in python. The files are large ~ 2G. ( I am moving DB data ). So far I have</p>
<pre><code>import codecs
infile = codecs.open(tmpfile, 'r', encoding='latin1')
outfile = codecs.open(tmpfile1, 'w', encoding='utf-8')
for line in infile:
outfile.write(line)
... | 4 | 2010-03-08T21:22:24Z | 2,405,126 | <p>You could use blocks larger than one line, and do binary I/O -- each might speed thinks up a bit (though on Linux binary I/O won't, as it's identical to text I/O):</p>
<pre><code> BLOCKSIZE = 1024*1024
with open(tmpfile, 'rb') as inf:
with open(tmpfile, 'wb') as ouf:
while True:
data = inf.read(BLOC... | 4 | 2010-03-08T22:02:30Z | [
"python"
] |
Fastest way to convert file from latin1 to utf-8 in python | 2,404,855 | <p>I need fastest way to convert files from latin1 to utf-8 in python. The files are large ~ 2G. ( I am moving DB data ). So far I have</p>
<pre><code>import codecs
infile = codecs.open(tmpfile, 'r', encoding='latin1')
outfile = codecs.open(tmpfile1, 'w', encoding='utf-8')
for line in infile:
outfile.write(line)
... | 4 | 2010-03-08T21:22:24Z | 2,405,150 | <p>If you are desperate to do it in Python (or any other language), at least do the I/O in bigger chunks than lines, and avoid the codecs overhead.</p>
<pre><code>infile = open(tmpfile, 'rb')
outfile = open(tmpfile1, 'wb')
BLOCKSIZE = 65536 # experiment with size
while True:
block = infile.read(BLOCKSIZE)
if n... | 2 | 2010-03-08T22:06:24Z | [
"python"
] |
How to check if text is "empty" (spaces, tabs, newlines) in Python? | 2,405,292 | <p>How can I test if the string is empty in Python?</p>
<p>For example,</p>
<p><code>"<space><space><space>"</code> is empty, so is</p>
<p><code>"<space><tab><space><newline><space>"</code>, so is</p>
<p><code>"<newline><newline><newline><tab>&... | 78 | 2010-03-08T22:29:25Z | 2,405,300 | <pre><code>yourString.isspace()
</code></pre>
<p>"Return true if there are only whitespace characters in the string and there is at least one character, false otherwise."</p>
<p>Combine that with a special case for handling the empty string.</p>
<p>Alternatively, you could use</p>
<pre><code>strippedString = yourSt... | 130 | 2010-03-08T22:30:44Z | [
"python",
"text",
"newline",
"tabs",
"space"
] |
How to check if text is "empty" (spaces, tabs, newlines) in Python? | 2,405,292 | <p>How can I test if the string is empty in Python?</p>
<p>For example,</p>
<p><code>"<space><space><space>"</code> is empty, so is</p>
<p><code>"<space><tab><space><newline><space>"</code>, so is</p>
<p><code>"<newline><newline><newline><tab>&... | 78 | 2010-03-08T22:29:25Z | 2,405,306 | <p><a href="http://docs.python.org/3.1/library/stdtypes.html#str.isspace"><code>isspace</code></a></p>
| 17 | 2010-03-08T22:31:15Z | [
"python",
"text",
"newline",
"tabs",
"space"
] |
How to check if text is "empty" (spaces, tabs, newlines) in Python? | 2,405,292 | <p>How can I test if the string is empty in Python?</p>
<p>For example,</p>
<p><code>"<space><space><space>"</code> is empty, so is</p>
<p><code>"<space><tab><space><newline><space>"</code>, so is</p>
<p><code>"<newline><newline><newline><tab>&... | 78 | 2010-03-08T22:29:25Z | 2,405,774 | <pre><code>>>> tests = ['foo', ' ', '\r\n\t', '', None]
>>> [bool(not s or s.isspace()) for s in tests]
[False, True, True, True, True]
>>>
</code></pre>
| 19 | 2010-03-09T00:19:22Z | [
"python",
"text",
"newline",
"tabs",
"space"
] |
How to check if text is "empty" (spaces, tabs, newlines) in Python? | 2,405,292 | <p>How can I test if the string is empty in Python?</p>
<p>For example,</p>
<p><code>"<space><space><space>"</code> is empty, so is</p>
<p><code>"<space><tab><space><newline><space>"</code>, so is</p>
<p><code>"<newline><newline><newline><tab>&... | 78 | 2010-03-08T22:29:25Z | 27,873,288 | <p>You want to use the <a href="https://docs.python.org/2/library/stdtypes.html#str.isspace"><code>isspace()</code></a> method</p>
<blockquote>
<p>str.<strong>isspace()</strong></p>
<p>Return true if there are only whitespace characters in the string and
there is at least one character, false otherwise.</p>
<... | 6 | 2015-01-10T05:47:01Z | [
"python",
"text",
"newline",
"tabs",
"space"
] |
How to check if text is "empty" (spaces, tabs, newlines) in Python? | 2,405,292 | <p>How can I test if the string is empty in Python?</p>
<p>For example,</p>
<p><code>"<space><space><space>"</code> is empty, so is</p>
<p><code>"<space><tab><space><newline><space>"</code>, so is</p>
<p><code>"<newline><newline><newline><tab>&... | 78 | 2010-03-08T22:29:25Z | 28,312,484 | <p>Check the length of list given by of split() method.</p>
<pre><code>if (len(your_string.split())==0:
print("yes")
</code></pre>
<p>Or
Compare output of strip() method with null.</p>
<pre><code>if (your_string.srip())=='':
print("yes")
</code></pre>
| 3 | 2015-02-04T02:24:54Z | [
"python",
"text",
"newline",
"tabs",
"space"
] |
How to check if text is "empty" (spaces, tabs, newlines) in Python? | 2,405,292 | <p>How can I test if the string is empty in Python?</p>
<p>For example,</p>
<p><code>"<space><space><space>"</code> is empty, so is</p>
<p><code>"<space><tab><space><newline><space>"</code>, so is</p>
<p><code>"<newline><newline><newline><tab>&... | 78 | 2010-03-08T22:29:25Z | 28,433,369 | <p>for those who expect a behaviour like the apache <a href="http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isBlank(java.lang.CharSequence)" rel="nofollow">StringUtils.isBlank</a> or Guava <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/... | 4 | 2015-02-10T13:53:14Z | [
"python",
"text",
"newline",
"tabs",
"space"
] |
Own help message using optparse | 2,405,351 | <p>is possible to make own help message or attach own event on help option using optparse module in Python?</p>
| 2 | 2010-03-08T22:40:51Z | 2,405,448 | <p>You should be able to replace the default help mechanism with your own merely by subclassing <code>OptionParser</code> and overriding the <a href="http://docs.python.org/library/optparse.html#generating-help" rel="nofollow"><code>print_help()</code></a> method.</p>
| 1 | 2010-03-08T22:59:33Z | [
"python",
"optparse"
] |
Own help message using optparse | 2,405,351 | <p>is possible to make own help message or attach own event on help option using optparse module in Python?</p>
| 2 | 2010-03-08T22:40:51Z | 2,405,457 | <p>Sure - just use the params to the OptionParser constructor:</p>
<pre><code>import optparse
help_text = """
Hi, this is a really long help message for %prog.
It's a pretty ace thing. (C)2010 Stuff etc.
"""
parser = optparse.OptionParser(usage=help_text, version="%prog 1.0 beta")
(options, args) = parser.parse_arg... | 3 | 2010-03-08T23:00:10Z | [
"python",
"optparse"
] |
Own help message using optparse | 2,405,351 | <p>is possible to make own help message or attach own event on help option using optparse module in Python?</p>
| 2 | 2010-03-08T22:40:51Z | 26,190,891 | <p>For custom help messages I ignore <a href="https://hg.python.org/cpython/file/2.7/Lib/optparse.py" rel="nofollow">optparse</a> altogether:</p>
<pre><code>import os
import sys
from optparse import OptionParser
__version__ = '1.0'
progname = os.path.basename(sys.argv[0])
usage = """\
usage: %s [options] URL
op... | 0 | 2014-10-04T08:02:48Z | [
"python",
"optparse"
] |
How do I override __getattr__ in Python without breaking the default behavior? | 2,405,590 | <p>I want to override the <code>__getattr__</code> method on a class to do something fancy but I don't want to break the default behavior.</p>
<p>What's the correct way to do this?</p>
| 130 | 2010-03-08T23:29:32Z | 2,405,617 | <p>Overriding <code>__getattr__</code> should be fine -- <code>__getattr__</code> is only called as a last resort i.e. if there are no attributes in the instance that match the name. For instance, if you access <code>foo.bar</code>, then <code>__getattr__</code> will only be called if <code>foo</code> has no attribute ... | 200 | 2010-03-08T23:35:42Z | [
"python"
] |
How do I override __getattr__ in Python without breaking the default behavior? | 2,405,590 | <p>I want to override the <code>__getattr__</code> method on a class to do something fancy but I don't want to break the default behavior.</p>
<p>What's the correct way to do this?</p>
| 130 | 2010-03-08T23:29:32Z | 2,405,667 | <pre><code>class A(object):
def __init__(self):
self.a = 42
def __getattr__(self, attr):
if attr in ["b", "c"]:
return 42
raise AttributeError("%r object has no attribute %r" %
(self.__class__, attr))
# exception text copied from Python2.6
</code></pre>
<hr>
<pre><c... | 26 | 2010-03-08T23:50:51Z | [
"python"
] |
How do I override __getattr__ in Python without breaking the default behavior? | 2,405,590 | <p>I want to override the <code>__getattr__</code> method on a class to do something fancy but I don't want to break the default behavior.</p>
<p>What's the correct way to do this?</p>
| 130 | 2010-03-08T23:29:32Z | 31,944,601 | <p>To extend Michael answer, if you want to maintain the default behavior using <code>__getattr__</code>, you can do it like so: </p>
<pre><code>class Foo(object):
def __getattr__(self, name):
if name == 'something':
return 42
# Default behaviour
return self.__getattribute__(n... | 2 | 2015-08-11T14:30:27Z | [
"python"
] |
Why would memcached refuse to store data with some keys? | 2,405,621 | <p>I use the memcache extension for python, and I have a very strange problem. Memcached refuses to store the exact same data with some keys, and succeeds in caching some others.</p>
<pre><code>>>> import memcache
>>> conn = memcache.Client('121.0.0.1:11211', debug=0)
>>> conn.set('138b9c95d... | 1 | 2010-03-08T23:36:41Z | 2,405,690 | <p>The first param should be a list</p>
<pre><code>conn = memcache.Client(['127.0.0.1:11211'], debug=0)
</code></pre>
| 1 | 2010-03-08T23:57:37Z | [
"python",
"ubuntu",
"memcached"
] |
Python: how to switch between workspaces using Xlib? | 2,405,738 | <p>how do I switch between my window manager's workspaces using Python with Xlib module?</p>
<p>I've been searching Google the last couple of hours, and this is my most promising attempt:</p>
<pre><code>#!/usr/bin/python
from Xlib import X, display, error, Xatom, Xutil
import Xlib.protocol.event
screen = Xlib.displ... | 4 | 2010-03-09T00:10:23Z | 2,410,996 | <p>Apparently you need to work on the same Display object and then <code>flush</code> it at the end. Something like:</p>
<pre><code>display = Xlib.display.Display()
screen = display.screen()
root = screen.root
# ...
sendEvent(root, display.intern_atom("_NET_CURRENT_DESKTOP"), [1, X.CurrentTime])
display.flush()
</co... | 1 | 2010-03-09T17:17:26Z | [
"python",
"window",
"pygtk",
"manager",
"xlib"
] |
How to stop a QDialog from executing while still in the __init__ statement (or immediately after)? | 2,405,750 | <p>I am wondering how I can go about stopping a dialog from opening if certain conditions are met in its <code>__init__</code> statement.</p>
<p>The following code tries to call the 'self.close()' function and it does, but (I'm assuming) since the dialog has not yet started its event loop, that it doesn't trigger the ... | 0 | 2010-03-09T00:14:39Z | 2,453,561 | <p>The dialog will be run only if exec_ method is called. You should therefore check conditions in the exec_ method and if they are met, run exec_ from QDialog.</p>
<p>Other method is to raise an exception inside the constructor (though I am not sure, it is a good practice; in other languages you generally shouldn't a... | 1 | 2010-03-16T10:32:40Z | [
"python",
"pyqt4",
"qdialog"
] |
Python: Indexing list for element in nested list | 2,405,928 | <p>I know what I'm looking for. I want python to tell me which list it's in.</p>
<p>Here's some pseudocode:</p>
<pre><code>item = "a"
nested_list = [["a", "b"], ["c", "d"]]
list.index(item) #obviously this doesn't work
</code></pre>
<p>here I would want python to return 0 (because "a" is an element in the first s... | 10 | 2010-03-09T00:53:06Z | 2,405,944 | <p>You'll need to use a looping construct of some sort:</p>
<pre><code>next((sublist for sublist in mainlist if item in sublist))
</code></pre>
<p>That will give you a generator for all sublists containing the item you want, and give you the first one.</p>
| 1 | 2010-03-09T00:56:14Z | [
"python",
"indexing",
"list",
"nested"
] |
Python: Indexing list for element in nested list | 2,405,928 | <p>I know what I'm looking for. I want python to tell me which list it's in.</p>
<p>Here's some pseudocode:</p>
<pre><code>item = "a"
nested_list = [["a", "b"], ["c", "d"]]
list.index(item) #obviously this doesn't work
</code></pre>
<p>here I would want python to return 0 (because "a" is an element in the first s... | 10 | 2010-03-09T00:53:06Z | 2,405,951 | <p>In Python 2.6 or better,</p>
<pre><code>next((i for i, sublist in enumerate(nested_list) if "a" in sublist), -1)
</code></pre>
<p>assuming e.g. you want a <code>-1</code> result if <code>'a'</code> is present in none of the sublists.</p>
<p>Of course it can be done in older versions of Python, too, but not quite ... | 12 | 2010-03-09T00:57:39Z | [
"python",
"indexing",
"list",
"nested"
] |
Python: Indexing list for element in nested list | 2,405,928 | <p>I know what I'm looking for. I want python to tell me which list it's in.</p>
<p>Here's some pseudocode:</p>
<pre><code>item = "a"
nested_list = [["a", "b"], ["c", "d"]]
list.index(item) #obviously this doesn't work
</code></pre>
<p>here I would want python to return 0 (because "a" is an element in the first s... | 10 | 2010-03-09T00:53:06Z | 2,405,961 | <p>Iterate over the list to get each sublist. Then, check to see if the item is in the sublist:</p>
<pre><code>for i in range(0,len(list)):
if whatYoureLookingFor in list[i]:
print i
</code></pre>
| 0 | 2010-03-09T00:59:11Z | [
"python",
"indexing",
"list",
"nested"
] |
Python: Indexing list for element in nested list | 2,405,928 | <p>I know what I'm looking for. I want python to tell me which list it's in.</p>
<p>Here's some pseudocode:</p>
<pre><code>item = "a"
nested_list = [["a", "b"], ["c", "d"]]
list.index(item) #obviously this doesn't work
</code></pre>
<p>here I would want python to return 0 (because "a" is an element in the first s... | 10 | 2010-03-09T00:53:06Z | 2,405,969 | <pre><code>>>> nested_list = [["a", "b"], ["c", "d"]]
>>> item="a"
>>> for o,sublist in enumerate(nested_list):
... if item in sublist:
... print o
...
0
</code></pre>
| 0 | 2010-03-09T01:00:44Z | [
"python",
"indexing",
"list",
"nested"
] |
Use of infix operator hack in production code (Python) | 2,405,936 | <p>What is your opinion of using the <a href="http://code.activestate.com/recipes/384122-infix-operators/" rel="nofollow">infix operator hack</a> in production code? Issues:</p>
<ul>
<li>The effect this will have on speed.</li>
<li>The potential for a clashes with an object with these operators already defined. This s... | 0 | 2010-03-09T00:55:16Z | 2,405,968 | <p>In my personal opinion this would not be a great idea in production code: the biggest problem with it is that it totally non-standard and will probably leave non-familiar readers wondering where this novel syntax has suddenly sprung from.</p>
<p>I think you should prefer clarity rather than succinctness in general ... | 1 | 2010-03-09T01:00:40Z | [
"python"
] |
Use of infix operator hack in production code (Python) | 2,405,936 | <p>What is your opinion of using the <a href="http://code.activestate.com/recipes/384122-infix-operators/" rel="nofollow">infix operator hack</a> in production code? Issues:</p>
<ul>
<li>The effect this will have on speed.</li>
<li>The potential for a clashes with an object with these operators already defined. This s... | 0 | 2010-03-09T00:55:16Z | 2,405,976 | <p>It will be measurably slower than more Pythonic code, fragile (e.g. in the way you suggest), and baffling to every expert Python programmer that comes upon such code for the first time.</p>
<p>If you want to turn Python into one of the very few languages that allow user-defined infix operators (such as Haskell), yo... | 6 | 2010-03-09T01:04:09Z | [
"python"
] |
Python Naming Conventions for Dictionaries/Maps/Hashes | 2,405,958 | <p>While other questions have tackled the broader category of <a href="http://stackoverflow.com/questions/659415/python-sequence-naming-convention">sequences</a> and <a href="http://stackoverflow.com/questions/711884/python-naming-conventions-for-modules">modules</a>, I ask this very specific question:</p>
<p><strong>... | 24 | 2010-03-09T00:58:38Z | 2,405,972 | <p>I usually use <something><code>map</code> since it's usually a map such as strings to functions, or numbers to classes, or whatnot. Unnamed dicts usually end up in a larger structure, so I don't worry about them.</p>
| 1 | 2010-03-09T01:02:46Z | [
"python",
"dictionary",
"naming-conventions",
"mapping"
] |
Python Naming Conventions for Dictionaries/Maps/Hashes | 2,405,958 | <p>While other questions have tackled the broader category of <a href="http://stackoverflow.com/questions/659415/python-sequence-naming-convention">sequences</a> and <a href="http://stackoverflow.com/questions/711884/python-naming-conventions-for-modules">modules</a>, I ask this very specific question:</p>
<p><strong>... | 24 | 2010-03-09T00:58:38Z | 2,405,985 | <p>I never seem to name them anything like what you proposed (i.e. keeping one way). It just seems to be much more clear when I can find a "proper name" for the hash. It might be "person_details" or "file_sizes" or "album_tracks" etc. (although the last 2 seem to have key_value names, first one a bit less). In rare cas... | 3 | 2010-03-09T01:06:55Z | [
"python",
"dictionary",
"naming-conventions",
"mapping"
] |
Python Naming Conventions for Dictionaries/Maps/Hashes | 2,405,958 | <p>While other questions have tackled the broader category of <a href="http://stackoverflow.com/questions/659415/python-sequence-naming-convention">sequences</a> and <a href="http://stackoverflow.com/questions/711884/python-naming-conventions-for-modules">modules</a>, I ask this very specific question:</p>
<p><strong>... | 24 | 2010-03-09T00:58:38Z | 2,406,263 | <p>I think it makes sense to name the dict after the values in the dict, and drop any mention of the key. After all, you are going to be using the dict in situations like <code>values[key]</code> which makes it perfectly clear what the keys are, assuming you named <code>key</code> well.</p>
| 2 | 2010-03-09T02:26:38Z | [
"python",
"dictionary",
"naming-conventions",
"mapping"
] |
Python Naming Conventions for Dictionaries/Maps/Hashes | 2,405,958 | <p>While other questions have tackled the broader category of <a href="http://stackoverflow.com/questions/659415/python-sequence-naming-convention">sequences</a> and <a href="http://stackoverflow.com/questions/711884/python-naming-conventions-for-modules">modules</a>, I ask this very specific question:</p>
<p><strong>... | 24 | 2010-03-09T00:58:38Z | 29,093,203 | <p><code>key_to_value</code>, for example <code>surname_to_salary</code> may be useful when there are closely interrelated maps in code: a to b, b to a, c to b etc.</p>
| 7 | 2015-03-17T07:08:24Z | [
"python",
"dictionary",
"naming-conventions",
"mapping"
] |
Detecting circular imports | 2,406,007 | <p>I'm working with a project that contains about 30 unique modules. It wasn't designed too well, so it's common that I create circular imports when adding some new functionality to the project.</p>
<p>Of course, when I add the circular import, I'm unaware of it. Sometimes it's pretty obvious I've made a circular impo... | 10 | 2010-03-09T01:11:14Z | 2,406,034 | <p>Not all circular imports are a problem, as you've found when an exception is not thrown.</p>
<p>When they are a problem, you'll get an exception the next time you try to run any of your tests. You can change the code when this happens.</p>
<p>I don't see any change required from this situation.</p>
<p>Example of... | 1 | 2010-03-09T01:19:55Z | [
"python",
"circular-dependency"
] |
Detecting circular imports | 2,406,007 | <p>I'm working with a project that contains about 30 unique modules. It wasn't designed too well, so it's common that I create circular imports when adding some new functionality to the project.</p>
<p>Of course, when I add the circular import, I'm unaware of it. Sometimes it's pretty obvious I've made a circular impo... | 10 | 2010-03-09T01:11:14Z | 2,406,037 | <p><code>import</code> uses <code>__builtin__.__import__()</code>, so if you monkeypatch that then every import everywhere will pick up the changes. Note that a circular import is <strong>not</strong> necessarily a problem though.</p>
| 0 | 2010-03-09T01:20:21Z | [
"python",
"circular-dependency"
] |
Detecting circular imports | 2,406,007 | <p>I'm working with a project that contains about 30 unique modules. It wasn't designed too well, so it's common that I create circular imports when adding some new functionality to the project.</p>
<p>Of course, when I add the circular import, I'm unaware of it. Sometimes it's pretty obvious I've made a circular impo... | 10 | 2010-03-09T01:11:14Z | 2,406,043 | <p>To avoid having to alter every module, you could stick your import-tracking functionality in a <a href="http://www.python.org/dev/peps/pep-0302/" rel="nofollow">import hook</a>, or in a customized <code>__import__</code> you could stick in the built-ins -- the latter, for once, might work better, because <code>__imp... | 4 | 2010-03-09T01:22:03Z | [
"python",
"circular-dependency"
] |
Detecting circular imports | 2,406,007 | <p>I'm working with a project that contains about 30 unique modules. It wasn't designed too well, so it's common that I create circular imports when adding some new functionality to the project.</p>
<p>Of course, when I add the circular import, I'm unaware of it. Sometimes it's pretty obvious I've made a circular impo... | 10 | 2010-03-09T01:11:14Z | 2,406,056 | <p>Circular imports in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow">Python</a> are not like PHP includes.</p>
<p>Python imported modules are loaded the first time into an import "handler", and kept there for the duration of the process. This handler assigns names in the local... | 1 | 2010-03-09T01:28:47Z | [
"python",
"circular-dependency"
] |
Get the last '/' or '\\' character in Python | 2,406,032 | <p>If I have a string that looks like either</p>
<pre><code>./A/B/c.d
</code></pre>
<p>OR</p>
<pre><code>.\A\B\c.d
</code></pre>
<p>How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed.</p>
<p>This problem kinda boils down to: How do I get the last of a specific char... | 2 | 2010-03-09T01:19:18Z | 2,406,041 | <p>Normally <a href="http://docs.python.org/library/os.path.html#os.path.dirname"><code>os.path.dirname()</code></a> is used for this.</p>
| 7 | 2010-03-09T01:21:39Z | [
"python",
"string"
] |
Get the last '/' or '\\' character in Python | 2,406,032 | <p>If I have a string that looks like either</p>
<pre><code>./A/B/c.d
</code></pre>
<p>OR</p>
<pre><code>.\A\B\c.d
</code></pre>
<p>How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed.</p>
<p>This problem kinda boils down to: How do I get the last of a specific char... | 2 | 2010-03-09T01:19:18Z | 2,406,042 | <p>I believe you are looking for <a href="http://docs.python.org/library/os.path.html#os.path.split" rel="nofollow">os.path.split</a>. It splits the path into head and tail... tail being the file, head being the path up to the file.</p>
| 4 | 2010-03-09T01:21:49Z | [
"python",
"string"
] |
Get the last '/' or '\\' character in Python | 2,406,032 | <p>If I have a string that looks like either</p>
<pre><code>./A/B/c.d
</code></pre>
<p>OR</p>
<pre><code>.\A\B\c.d
</code></pre>
<p>How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed.</p>
<p>This problem kinda boils down to: How do I get the last of a specific char... | 2 | 2010-03-09T01:19:18Z | 2,406,045 | <pre><code>>>> p="./A/B/c.d"
>>> import os
>>> os.path.split(p)
('./A/B', 'c.d')
>>> os.path.split(p)[0]
'./A/B'
>>> os.path.dirname(p)
'./A/B'
>>> p.rsplit("/",1)[0]
'./A/B
</code></pre>
| 2 | 2010-03-09T01:23:24Z | [
"python",
"string"
] |
Setting up a python screen scraper that could work on Google App engine | 2,406,082 | <p>I am looking to setup a automated screen scraper that will run on Google app engine using python. I want it to scrape the site and put the specified results into a Entity in app engine. I am looking for some directions on what to use. I have seen beautifulsoup but wonder if people could recommend anything else that ... | 3 | 2010-03-09T01:38:14Z | 2,406,093 | <p>The other choice is <code>lxml</code>, but it uses C code and so does not work on GAE.</p>
| 0 | 2010-03-09T01:42:13Z | [
"python",
"google-app-engine",
"screen-scraping"
] |
Setting up a python screen scraper that could work on Google App engine | 2,406,082 | <p>I am looking to setup a automated screen scraper that will run on Google app engine using python. I want it to scrape the site and put the specified results into a Entity in app engine. I am looking for some directions on what to use. I have seen beautifulsoup but wonder if people could recommend anything else that ... | 3 | 2010-03-09T01:38:14Z | 2,406,255 | <p><a href="http://www.crummy.com/software/BeautifulSoup/3.1-problems.html">Beautifulsoup</a> runs fine on App Engine (just make sure to use 3.0.8, not the iffy 3.1.0). The main alternative, I think, would be <a href="http://code.google.com/p/html5lib/">html5lib</a> -- I haven't tries it on App Engine but I believe it ... | 4 | 2010-03-09T02:24:30Z | [
"python",
"google-app-engine",
"screen-scraping"
] |
Setting up a python screen scraper that could work on Google App engine | 2,406,082 | <p>I am looking to setup a automated screen scraper that will run on Google app engine using python. I want it to scrape the site and put the specified results into a Entity in app engine. I am looking for some directions on what to use. I have seen beautifulsoup but wonder if people could recommend anything else that ... | 3 | 2010-03-09T01:38:14Z | 2,660,349 | <p>I have used BeautifulSoup with great success parsing HTML. Problem is that's all BeautifulSoup does, is parse the HTML. I ended up writing all the http interactions using urlfetch. </p>
<p>To web-scrape my target I need a full fledged code driven browser that can execute javascript on my target site's pages. I ... | 0 | 2010-04-17T22:41:36Z | [
"python",
"google-app-engine",
"screen-scraping"
] |
Setting up a python screen scraper that could work on Google App engine | 2,406,082 | <p>I am looking to setup a automated screen scraper that will run on Google app engine using python. I want it to scrape the site and put the specified results into a Entity in app engine. I am looking for some directions on what to use. I have seen beautifulsoup but wonder if people could recommend anything else that ... | 3 | 2010-03-09T01:38:14Z | 3,947,242 | <p>I have had good (although slow) results using mechanize and BeautifulSoup. In fact, to save code space on Google App Engine, I use the (old) version of BeautifulSoup included in mechanize.</p>
<p>I have mechanize in a zip file, <code>mechanize.zip</code>. The index of this zip file looks like:</p>
<pre><code>mecha... | 1 | 2010-10-16T01:22:22Z | [
"python",
"google-app-engine",
"screen-scraping"
] |
Getting readline to block on a FIFO | 2,406,365 | <p>I create a fifo:</p>
<pre><code>mkfifo tofetch
</code></pre>
<p>I run this python code:</p>
<pre><code>fetchlistfile = file("tofetch", "r")
while 1:
nextfetch = fetchlistfile.readline()
print nextfetch
</code></pre>
<p>It stalls on readline, as I would hope. I run:</p>
<pre><code>echo "test" > tofetc... | 4 | 2010-03-09T03:01:32Z | 2,406,429 | <p>According to the documentation for <a href="http://docs.python.org/library/stdtypes.html#file.readline" rel="nofollow">readline</a>, it returns the empty string if and only if you're at end-of-file. Closed isn't the same as end-of-file. The file object will only be closed when you call .close(). When your code re... | 4 | 2010-03-09T03:22:44Z | [
"python",
"pipe",
"fifo"
] |
Implementing a Patricia Trie for use as a dictionary | 2,406,416 | <p>I'm attempting to implement a Patricia Trie with the methods <code>addWord()</code>, <code>isWord()</code>, and <code>isPrefix()</code> as a means to store a large dictionary of words for quick retrieval (including prefix search). I've read up on the concepts but they just aren't clarifying into an implementation. I... | 9 | 2010-03-09T03:20:46Z | 2,412,468 | <p>Someone else asked a question about Patricia tries a while ago and I thought about making a Python implementation then, but this time I decided to actually give it a shot (Yes, this is way overboard, but it seemed like a nice little project). What I have made is perhaps not a pure Patricia trie implementation, but I... | 9 | 2010-03-09T20:51:45Z | [
"java",
"python",
"trie",
"patricia-trie",
"radix"
] |
Implementing a Patricia Trie for use as a dictionary | 2,406,416 | <p>I'm attempting to implement a Patricia Trie with the methods <code>addWord()</code>, <code>isWord()</code>, and <code>isPrefix()</code> as a means to store a large dictionary of words for quick retrieval (including prefix search). I've read up on the concepts but they just aren't clarifying into an implementation. I... | 9 | 2010-03-09T03:20:46Z | 16,047,512 | <p>Here's a recursive implementation using more pythonic methods:</p>
<pre><code>def matching_prefix_index(word1, word2):
max_len = min(len(word1),len(word2))
for i in range(max_len):
if word2[i] != word1[i]:
return i
return max_len
class PatriciaTrie(object):
def __init__(self):
... | 1 | 2013-04-16T21:33:27Z | [
"java",
"python",
"trie",
"patricia-trie",
"radix"
] |
Google App Engine: Users API acting oddly | 2,406,424 | <p>I think I'm using the Users API incorrectly:</p>
<pre><code>class BaseHandler(webapp.RequestHandler):
user = users.get_current_user()
def header(self, title):
if self.user:
render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
else:
render('Views... | 1 | 2010-03-09T03:22:06Z | 2,409,242 | <p>You are storing the result of <code>users.get_current_user()</code> in the variable called <code>user</code>, but then your <code>if</code> checks the value of <code>self.user</code>, which is not the same variable.</p>
<p>Use the same variable name and all should be fine!</p>
| 1 | 2010-03-09T13:19:30Z | [
"python",
"django",
"google-app-engine"
] |
I want to scrape a site using GAE and post the results into a Google Entity | 2,406,428 | <p>I want to scrape this URL : <a href="https://www.xstreetsl.com/modules.php?searchSubmitImage_x=0&searchSubmitImage_y=0&SearchLocale=0&name=Marketplace&SearchKeyword=business&searchSubmitImage.x=0&searchSubmitImage.y=0&SearchLocale=0&SearchPriceMin=&SearchPriceMax=&SearchRating... | 1 | 2010-03-09T03:22:41Z | 2,406,466 | <p>There are several nice screen scraping libraries you can use in Python. </p>
<p>Perhaps the easiest to knock up an advanced scraper with is <a href="http://scrapy.org/" rel="nofollow">scrapy</a>. It relies on <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> to implement the main engine but prov... | 3 | 2010-03-09T03:34:54Z | [
"python",
"google-app-engine",
"screen-scraping"
] |
I want to scrape a site using GAE and post the results into a Google Entity | 2,406,428 | <p>I want to scrape this URL : <a href="https://www.xstreetsl.com/modules.php?searchSubmitImage_x=0&searchSubmitImage_y=0&SearchLocale=0&name=Marketplace&SearchKeyword=business&searchSubmitImage.x=0&searchSubmitImage.y=0&SearchLocale=0&SearchPriceMin=&SearchPriceMax=&SearchRating... | 1 | 2010-03-09T03:22:41Z | 2,406,929 | <p>For normalizing HTML using a pure Python library I have had better experiences with <a href="http://code.google.com/p/html5lib/" rel="nofollow">html5lib</a> than BeautifulSoup.</p>
<p>However you just want to extract simply structured information, which doesn't actually require normalizing the HTML. I have a few sc... | 3 | 2010-03-09T05:45:18Z | [
"python",
"google-app-engine",
"screen-scraping"
] |
Django formsets: make first required? | 2,406,537 | <p>These formsets are exhibiting exactly the <em>opposite</em> behavior that I want.</p>
<p>My view is set up like this:</p>
<pre><code>def post(request): # TODO: handle vehicle formset
VehicleFormSetFactory = formset_factory(VehicleForm, extra=1)
if request.POST:
vehicles_formset = VehicleFormSetFact... | 28 | 2010-03-09T03:52:21Z | 2,406,659 | <p>Oh I think I see. Try this:</p>
<pre><code>from django.forms.formsets import BaseFormSet, formset_factory
class OneExtraRequiredFormSet(BaseFormSet):
def initial_form_count(self):
return max(super(OneExtraRequiredFormSet,self).initial_form_count() - 1,0)
VehicleFormSetFactory = formset_factory(VehicleF... | 1 | 2010-03-09T04:24:46Z | [
"python",
"django",
"django-forms"
] |
Django formsets: make first required? | 2,406,537 | <p>These formsets are exhibiting exactly the <em>opposite</em> behavior that I want.</p>
<p>My view is set up like this:</p>
<pre><code>def post(request): # TODO: handle vehicle formset
VehicleFormSetFactory = formset_factory(VehicleForm, extra=1)
if request.POST:
vehicles_formset = VehicleFormSetFact... | 28 | 2010-03-09T03:52:21Z | 2,422,221 | <p>Well... this makes the first form required.</p>
<pre><code>class RequiredFormSet(BaseFormSet):
def clean(self):
if any(self.errors):
return
if not self.forms[0].has_changed():
raise forms.ValidationError('Please add at least one vehicle.')
</code></pre>
<p>Only "problem... | 9 | 2010-03-11T02:57:37Z | [
"python",
"django",
"django-forms"
] |
Django formsets: make first required? | 2,406,537 | <p>These formsets are exhibiting exactly the <em>opposite</em> behavior that I want.</p>
<p>My view is set up like this:</p>
<pre><code>def post(request): # TODO: handle vehicle formset
VehicleFormSetFactory = formset_factory(VehicleForm, extra=1)
if request.POST:
vehicles_formset = VehicleFormSetFact... | 28 | 2010-03-09T03:52:21Z | 4,951,032 | <p>Found a better solution:</p>
<pre><code>class RequiredFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
super(RequiredFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
</code></pre>
<p>Then create your formset like this:</p>
<pre... | 63 | 2011-02-09T22:00:41Z | [
"python",
"django",
"django-forms"
] |
Django formsets: make first required? | 2,406,537 | <p>These formsets are exhibiting exactly the <em>opposite</em> behavior that I want.</p>
<p>My view is set up like this:</p>
<pre><code>def post(request): # TODO: handle vehicle formset
VehicleFormSetFactory = formset_factory(VehicleForm, extra=1)
if request.POST:
vehicles_formset = VehicleFormSetFact... | 28 | 2010-03-09T03:52:21Z | 29,954,622 | <p>New in Django 1.7: you can specify this behaviour with your formset_factory</p>
<p><a href="https://docs.djangoproject.com/en/1.8/topics/forms/formsets/#validate-min">https://docs.djangoproject.com/en/1.8/topics/forms/formsets/#validate-min</a></p>
<pre><code>VehicleFormSetFactory = formset_factory(VehicleForm, mi... | 14 | 2015-04-29T21:09:49Z | [
"python",
"django",
"django-forms"
] |
Preferred way of defining properties in Python: property decorator or lambda? | 2,406,567 | <p>Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?</p>
<pre><code>@property
def total(self):
return self.field_1 + self.field_2
</code></pre>
<p>or</p>
<pre><code>total = property(lambda self: self.field_1 + self.field_2)
</code></pre>
| 32 | 2010-03-09T04:00:43Z | 2,406,592 | <p>The decorator form is probably best in the case you've shown, where you want to turn the method into a read-only property. The second case is better when you want to provide a setter/deleter/docstring as well as the getter or if you want to add a property that has a different name to the method it derives its value... | 20 | 2010-03-09T04:05:22Z | [
"python",
"lambda",
"properties",
"decorator"
] |
Preferred way of defining properties in Python: property decorator or lambda? | 2,406,567 | <p>Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?</p>
<pre><code>@property
def total(self):
return self.field_1 + self.field_2
</code></pre>
<p>or</p>
<pre><code>total = property(lambda self: self.field_1 + self.field_2)
</code></pre>
| 32 | 2010-03-09T04:00:43Z | 2,406,609 | <p>Don't use lambdas for this. The first is acceptable for a read-only property, the second is used with real methods for more complex cases.</p>
| 4 | 2010-03-09T04:09:18Z | [
"python",
"lambda",
"properties",
"decorator"
] |
Preferred way of defining properties in Python: property decorator or lambda? | 2,406,567 | <p>Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?</p>
<pre><code>@property
def total(self):
return self.field_1 + self.field_2
</code></pre>
<p>or</p>
<pre><code>total = property(lambda self: self.field_1 + self.field_2)
</code></pre>
| 32 | 2010-03-09T04:00:43Z | 2,407,006 | <p>For read-only properties I use the decorator, else I usually do something like this:</p>
<pre><code>class Bla(object):
def sneaky():
def fget(self):
return self._sneaky
def fset(self, value):
self._sneaky = value
return locals()
sneaky = property(**sneaky())
<... | 49 | 2010-03-09T06:11:05Z | [
"python",
"lambda",
"properties",
"decorator"
] |
Adding an object to another module's globals in python | 2,406,586 | <p>I know this is very evil, but is it possible to add an object to another module's globals, something like:</p>
<pre><code>#module dog.py
import cat
cat.globals.addVar('name','mittens')
</code></pre>
<p>and </p>
<pre><code>#module cat.py
print name #mittens
</code></pre>
| 2 | 2010-03-09T04:04:24Z | 2,406,598 | <pre><code>setattr(cat, 'name', 'mittens')
</code></pre>
<p>or</p>
<pre><code>cat.name = 'mittens'
</code></pre>
| 2 | 2010-03-09T04:06:57Z | [
"python",
"globals"
] |
How do I set a default page in Pylons? | 2,406,630 | <p>I've created a new Pylons application and added a controller ("main.py") with a template ("index.mako"). Now the URL <code>http://myserver/main/index</code> works. How do I make this the default page, ie. the one returned when I browse to <code>http://myserver/</code> ?</p>
<p>I've already added a default route in ... | 2 | 2010-03-09T04:14:28Z | 2,406,704 | <p>Try this: <code>map.connect('/', controller='main', action='index')</code></p>
| 3 | 2010-03-09T04:37:55Z | [
"python",
"routes",
"pylons"
] |
How do I set a default page in Pylons? | 2,406,630 | <p>I've created a new Pylons application and added a controller ("main.py") with a template ("index.mako"). Now the URL <code>http://myserver/main/index</code> works. How do I make this the default page, ie. the one returned when I browse to <code>http://myserver/</code> ?</p>
<p>I've already added a default route in ... | 2 | 2010-03-09T04:14:28Z | 3,303,775 | <p>You need to remove public/index.html file to make / routing rule work. Otherwise it is served directly.</p>
| 2 | 2010-07-21T20:54:24Z | [
"python",
"routes",
"pylons"
] |
Accented characters in Matplotlib | 2,406,700 | <p>Is there a way to get Matplotlib to render accented chars (é,ã,â,etc)?</p>
<p>For instance, I'm trying to use accented characters on <code>set_yticklabels()</code> and Matplotlib renders squares instead, and when I use <code>unicode()</code> it renders the wrong characters.</p>
<p>Is there a way to make this wo... | 17 | 2010-03-09T04:37:12Z | 2,406,765 | <p>Sure. You can use TeX:</p>
<pre><code>from matplotlib import rcParams
rcParams['text.usetex'] = True
ax = ... # Axes object
ax.set_yticklabels(['$\'{e}$', '$\tilde{a}$', '$\hat{a}$'])
</code></pre>
| 6 | 2010-03-09T04:56:45Z | [
"python",
"unicode",
"matplotlib"
] |
Accented characters in Matplotlib | 2,406,700 | <p>Is there a way to get Matplotlib to render accented chars (é,ã,â,etc)?</p>
<p>For instance, I'm trying to use accented characters on <code>set_yticklabels()</code> and Matplotlib renders squares instead, and when I use <code>unicode()</code> it renders the wrong characters.</p>
<p>Is there a way to make this wo... | 17 | 2010-03-09T04:37:12Z | 2,408,847 | <p>Prefix the strings with <code>u</code> to tell Python that they are Unicode strings:</p>
<pre><code>ax.set_yticklabels([u'é', u'ã', u'â'])
</code></pre>
| 14 | 2010-03-09T12:13:12Z | [
"python",
"unicode",
"matplotlib"
] |
Accented characters in Matplotlib | 2,406,700 | <p>Is there a way to get Matplotlib to render accented chars (é,ã,â,etc)?</p>
<p>For instance, I'm trying to use accented characters on <code>set_yticklabels()</code> and Matplotlib renders squares instead, and when I use <code>unicode()</code> it renders the wrong characters.</p>
<p>Is there a way to make this wo... | 17 | 2010-03-09T04:37:12Z | 14,390,347 | <p>I also had this problem specifically when I was trying to use the annotate function. Here was my error message:</p>
<pre><code>ValueError: matplotlib display text must have all code points < 128 or use Unicode strings
</code></pre>
<p>And here's what I used to resolve this:</p>
<pre><code>"accented string i.e.... | 3 | 2013-01-18T00:00:15Z | [
"python",
"unicode",
"matplotlib"
] |
Accented characters in Matplotlib | 2,406,700 | <p>Is there a way to get Matplotlib to render accented chars (é,ã,â,etc)?</p>
<p>For instance, I'm trying to use accented characters on <code>set_yticklabels()</code> and Matplotlib renders squares instead, and when I use <code>unicode()</code> it renders the wrong characters.</p>
<p>Is there a way to make this wo... | 17 | 2010-03-09T04:37:12Z | 15,974,746 | <p>from matplotlib import rc</p>
<pre><code>rcParams['text.latex.unicode']=True
</code></pre>
| 0 | 2013-04-12T15:02:36Z | [
"python",
"unicode",
"matplotlib"
] |
Why can you reference an imported module using the importing module in python | 2,406,722 | <p>I am trying to understand why any import can be referenced using the importing module, e.g</p>
<pre><code>#module master.py
import slave
</code></pre>
<p>and then</p>
<pre><code>>>>import master
>>>print master.slave
</code></pre>
<p>gives
<code><module 'slave' from 'C:\Documents and Setting... | 0 | 2010-03-09T04:43:07Z | 2,406,744 | <p>It's a side effect, but it can be used purposefully, e.g. <code>os.py</code> imports either <code>posixpath</code> or <code>ntpath</code> as <code>path</code> in order to create <code>os.path</code>.</p>
| 1 | 2010-03-09T04:50:19Z | [
"python",
"import",
"namespaces",
"module"
] |
Javascript equivalent of Python's iterkeys() dictionary method | 2,406,916 | <p>In Python I can use the <code>iterkeys()</code> method to iterate over the keys of a dictionary. For example:</p>
<pre><code>mydict = {'a': [3,5,6,43,3,6,3,],
'b': [87,65,3,45,7,8],
'c': [34,57,8,9,9,2],}
for k in mydict.iterkeys():
print k
</code></pre>
<p>gives me:</p>
<pre><code>a
c
b
<... | 4 | 2010-03-09T05:39:59Z | 2,406,922 | <pre><code>var mydict = {
'a': [3,5,6,43,3,6,3,],
'b': [87,65,3,45,7,8],
'c': [34,57,8,9,9,2],
};
for (var key in mydict) {
alert(key);
}
</code></pre>
| 4 | 2010-03-09T05:43:03Z | [
"javascript",
"python"
] |
Javascript equivalent of Python's iterkeys() dictionary method | 2,406,916 | <p>In Python I can use the <code>iterkeys()</code> method to iterate over the keys of a dictionary. For example:</p>
<pre><code>mydict = {'a': [3,5,6,43,3,6,3,],
'b': [87,65,3,45,7,8],
'c': [34,57,8,9,9,2],}
for k in mydict.iterkeys():
print k
</code></pre>
<p>gives me:</p>
<pre><code>a
c
b
<... | 4 | 2010-03-09T05:39:59Z | 2,406,923 | <pre><code>for(k in mydict){
alert(k)
}
</code></pre>
| 0 | 2010-03-09T05:43:19Z | [
"javascript",
"python"
] |
Why does concatenating a boolean value return an integer? | 2,406,959 | <p>In python, you can concatenate boolean values, and it would return an integer. Example:</p>
<pre><code>>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0
</code></pre>
<p>Why? Why does this ... | 8 | 2010-03-09T05:55:01Z | 2,406,969 | <p>Replace "concatenate" with "add" and <code>True</code>/<code>False</code> with <code>1</code>/<code>0</code>, as you've said, and it makes perfect sense.</p>
<blockquote>
<p>To sum up True and False in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that str()... | 7 | 2010-03-09T05:57:01Z | [
"python"
] |
Why does concatenating a boolean value return an integer? | 2,406,959 | <p>In python, you can concatenate boolean values, and it would return an integer. Example:</p>
<pre><code>>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0
</code></pre>
<p>Why? Why does this ... | 8 | 2010-03-09T05:55:01Z | 2,406,973 | <p>Because In Python, <code>bool</code> is the subclass/subtype of <code>int</code>.</p>
<pre><code>>>> issubclass(bool,int)
True
</code></pre>
<p><strong>Update</strong>:</p>
<p>From <a href="http://svn.python.org/projects/python/trunk/Objects/boolobject.c" rel="nofollow"><strong>boolobject.c</strong></a><... | 21 | 2010-03-09T05:58:41Z | [
"python"
] |
Why does concatenating a boolean value return an integer? | 2,406,959 | <p>In python, you can concatenate boolean values, and it would return an integer. Example:</p>
<pre><code>>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0
</code></pre>
<p>Why? Why does this ... | 8 | 2010-03-09T05:55:01Z | 2,406,974 | <pre><code>True is 1
False is 0
+ is ADD
</code></pre>
<p>Try this:</p>
<pre><code>IDLE 2.6.4
>>> True == 1
True
>>> False == 0
True
>>>
</code></pre>
| 2 | 2010-03-09T05:58:57Z | [
"python"
] |
Python urllib2 Basic Auth Problem | 2,407,126 | <p>Update: based on Lee's comment I decided to condense my code to a really simple script and run it from the command line:</p>
<pre><code>import urllib2
import sys
username = sys.argv[1]
password = sys.argv[2]
url = sys.argv[3]
print("calling %s with %s:%s\n" % (url, username, password))
passman = urllib2.HTTPPassw... | 57 | 2010-03-09T06:50:59Z | 2,407,165 | <p>The second parameter must be a URI, not a domain name. i.e.</p>
<pre><code>passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, "http://api.foursquare.com/", username, password)
</code></pre>
| 4 | 2010-03-09T06:57:53Z | [
"python",
"authentication",
"urllib2"
] |
Python urllib2 Basic Auth Problem | 2,407,126 | <p>Update: based on Lee's comment I decided to condense my code to a really simple script and run it from the command line:</p>
<pre><code>import urllib2
import sys
username = sys.argv[1]
password = sys.argv[2]
url = sys.argv[3]
print("calling %s with %s:%s\n" % (url, username, password))
passman = urllib2.HTTPPassw... | 57 | 2010-03-09T06:50:59Z | 2,955,687 | <p>The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.</p>
<p>Try using headers to... | 149 | 2010-06-02T07:18:38Z | [
"python",
"authentication",
"urllib2"
] |
Python urllib2 Basic Auth Problem | 2,407,126 | <p>Update: based on Lee's comment I decided to condense my code to a really simple script and run it from the command line:</p>
<pre><code>import urllib2
import sys
username = sys.argv[1]
password = sys.argv[2]
url = sys.argv[3]
print("calling %s with %s:%s\n" % (url, username, password))
passman = urllib2.HTTPPassw... | 57 | 2010-03-09T06:50:59Z | 24,048,852 | <p>(copy-paste/adapted from <a href="http://stackoverflow.com/a/24048772/1733117">http://stackoverflow.com/a/24048772/1733117</a>).</p>
<p>First you can subclass <code>urllib2.BaseHandler</code> or <code>urllib2.HTTPBasicAuthHandler</code>, and implement <code>http_request</code> so that each request has the appropria... | 3 | 2014-06-04T22:46:11Z | [
"python",
"authentication",
"urllib2"
] |
Python urllib2 Basic Auth Problem | 2,407,126 | <p>Update: based on Lee's comment I decided to condense my code to a really simple script and run it from the command line:</p>
<pre><code>import urllib2
import sys
username = sys.argv[1]
password = sys.argv[2]
url = sys.argv[3]
print("calling %s with %s:%s\n" % (url, username, password))
passman = urllib2.HTTPPassw... | 57 | 2010-03-09T06:50:59Z | 25,775,528 | <p>I would suggest that the current solution is to use my package <a href="https://pypi.python.org/pypi/urllib2_prior_auth/" rel="nofollow">urllib2_prior_auth</a> which solves this pretty nicely (I work on <a href="http://bugs.python.org/issue19494" rel="nofollow">inclusion</a> to the standard lib.</p>
| 0 | 2014-09-10T21:39:36Z | [
"python",
"authentication",
"urllib2"
] |
Python urllib2 Basic Auth Problem | 2,407,126 | <p>Update: based on Lee's comment I decided to condense my code to a really simple script and run it from the command line:</p>
<pre><code>import urllib2
import sys
username = sys.argv[1]
password = sys.argv[2]
url = sys.argv[3]
print("calling %s with %s:%s\n" % (url, username, password))
passman = urllib2.HTTPPassw... | 57 | 2010-03-09T06:50:59Z | 34,907,546 | <p>Here's what I'm using to deal with a similar problem I encountered while trying to access MailChimp's API. This does the same thing, just formatted nicer.</p>
<pre><code>import urllib2
import base64
chimpConfig = {
"headers" : {
"Content-Type": "application/json",
"Authorization": "Basic " + base64.enc... | 1 | 2016-01-20T18:17:49Z | [
"python",
"authentication",
"urllib2"
] |
Change Sikuli's sensitivity? | 2,407,212 | <p>I've been using sikuli for awhile, however I have an issue with it... It's not sensitive enough. I'm trying to match something on the screen that is -EXACT-, and there are a few other items on the screen that look similar enough that sikuli is mistaking them for what I'm actually looking for, so I need to make it lo... | 5 | 2010-03-09T07:10:20Z | 3,884,131 | <p>If you are using Sikuli IDE click image miniature, for which you want to change sensitivity. You will be presented screenshot of your desktop with and occurrences of pattern(your image). Below there is a slider witch changes sensitivity. While changing it you will notice that highlighted occurrences of the pattern i... | 3 | 2010-10-07T17:19:07Z | [
"python",
"sikuli"
] |
Change Sikuli's sensitivity? | 2,407,212 | <p>I've been using sikuli for awhile, however I have an issue with it... It's not sensitive enough. I'm trying to match something on the screen that is -EXACT-, and there are a few other items on the screen that look similar enough that sikuli is mistaking them for what I'm actually looking for, so I need to make it lo... | 5 | 2010-03-09T07:10:20Z | 3,885,229 | <p>You can do the following in the Sikuli IDE:</p>
<ul>
<li>Click on the image</li>
<li>In Pattern Settings > Matching Preview, drag the Similarity bar to 1.0 (all the way to the right)</li>
<li>Click OK</li>
</ul>
| 6 | 2010-10-07T19:35:06Z | [
"python",
"sikuli"
] |
Change Sikuli's sensitivity? | 2,407,212 | <p>I've been using sikuli for awhile, however I have an issue with it... It's not sensitive enough. I'm trying to match something on the screen that is -EXACT-, and there are a few other items on the screen that look similar enough that sikuli is mistaking them for what I'm actually looking for, so I need to make it lo... | 5 | 2010-03-09T07:10:20Z | 5,536,072 | <p>Will the following work?<br>
You are looking for the progress to reach 100% then loop again?</p>
<pre><code> f = open("C:\\test.htm",'W')
f.write('<font color="#347C2C">lOOPtEST</font><br />')
f.write('loop iteration' + (str (count)) + '<br />')
count = count + 1
f.close()
C... | 0 | 2011-04-04T08:19:45Z | [
"python",
"sikuli"
] |
Change Sikuli's sensitivity? | 2,407,212 | <p>I've been using sikuli for awhile, however I have an issue with it... It's not sensitive enough. I'm trying to match something on the screen that is -EXACT-, and there are a few other items on the screen that look similar enough that sikuli is mistaking them for what I'm actually looking for, so I need to make it lo... | 5 | 2010-03-09T07:10:20Z | 32,017,039 | <p>To match an exact image I use: </p>
<pre><code>image1 = ("image1.png")
while not exists (Pattern(image1).exact()):
# Wait until that exact image appears.
wait(1)
</code></pre>
| 0 | 2015-08-14T19:00:04Z | [
"python",
"sikuli"
] |
Python - merge items of two lists into a list of tuples | 2,407,398 | <p>What's the pythonic way of achieving the following?</p>
<pre><code>list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
#Need to create a of tuples from list_a and list_b
list_c = [(1,5), (2,6), (3,7), (4,8)]
</code></pre>
<p>Each member of list_c is a tuple, whose first member is from list_a and the second is from list_... | 108 | 2010-03-09T07:51:46Z | 2,407,405 | <pre><code>>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a, list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
</code></pre>
| 166 | 2010-03-09T07:52:50Z | [
"python",
"list",
"tuples"
] |
Python - merge items of two lists into a list of tuples | 2,407,398 | <p>What's the pythonic way of achieving the following?</p>
<pre><code>list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
#Need to create a of tuples from list_a and list_b
list_c = [(1,5), (2,6), (3,7), (4,8)]
</code></pre>
<p>Each member of list_c is a tuple, whose first member is from list_a and the second is from list_... | 108 | 2010-03-09T07:51:46Z | 2,407,425 | <p>Youre looking for the builtin function <a href="http://docs.python.org/library/functions.html#zip">zip</a>.</p>
| 7 | 2010-03-09T07:55:50Z | [
"python",
"list",
"tuples"
] |
Python - merge items of two lists into a list of tuples | 2,407,398 | <p>What's the pythonic way of achieving the following?</p>
<pre><code>list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
#Need to create a of tuples from list_a and list_b
list_c = [(1,5), (2,6), (3,7), (4,8)]
</code></pre>
<p>Each member of list_c is a tuple, whose first member is from list_a and the second is from list_... | 108 | 2010-03-09T07:51:46Z | 5,146,593 | <p>In python 3.0 zip returns a zip object. You can get a list out of it by calling <code>list(zip(a, b))</code>.</p>
| 33 | 2011-02-28T19:26:30Z | [
"python",
"list",
"tuples"
] |
Python - merge items of two lists into a list of tuples | 2,407,398 | <p>What's the pythonic way of achieving the following?</p>
<pre><code>list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
#Need to create a of tuples from list_a and list_b
list_c = [(1,5), (2,6), (3,7), (4,8)]
</code></pre>
<p>Each member of list_c is a tuple, whose first member is from list_a and the second is from list_... | 108 | 2010-03-09T07:51:46Z | 21,825,905 | <p>I know this is an old question and was already answered, but for some reason, I still wanna post this alternative solution. I know it's easy to just find out which built-in function does the "magic" you need, but it doesn't hurt to know you can do it by yourself. </p>
<pre><code>>>> list_1 = ['Ace', 'Ki... | 2 | 2014-02-17T10:01:33Z | [
"python",
"list",
"tuples"
] |
Python - merge items of two lists into a list of tuples | 2,407,398 | <p>What's the pythonic way of achieving the following?</p>
<pre><code>list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
#Need to create a of tuples from list_a and list_b
list_c = [(1,5), (2,6), (3,7), (4,8)]
</code></pre>
<p>Each member of list_c is a tuple, whose first member is from list_a and the second is from list_... | 108 | 2010-03-09T07:51:46Z | 31,217,379 | <p>You can use map lambda</p>
<pre><code>a = [2,3,4]
b = [5,6,7]
c = map(lambda x,y:(x,y),a,b)
</code></pre>
<p>This will also work if there lengths of original lists do not match</p>
| 4 | 2015-07-04T05:49:00Z | [
"python",
"list",
"tuples"
] |
Python - merge items of two lists into a list of tuples | 2,407,398 | <p>What's the pythonic way of achieving the following?</p>
<pre><code>list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
#Need to create a of tuples from list_a and list_b
list_c = [(1,5), (2,6), (3,7), (4,8)]
</code></pre>
<p>Each member of list_c is a tuple, whose first member is from list_a and the second is from list_... | 108 | 2010-03-09T07:51:46Z | 37,190,518 | <p>The output which you showed in problem statement is not the tuple but list</p>
<pre><code>list_c = [(1,5), (2,6), (3,7), (4,8)]
</code></pre>
<p>check for </p>
<pre><code>type(list_c)
</code></pre>
<p>considering you want the result as tuple out of list_a and list_b, do</p>
<pre><code>tuple(zip(list_a,list_b)) ... | 2 | 2016-05-12T14:52:22Z | [
"python",
"list",
"tuples"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.