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 |
|---|---|---|---|---|---|---|---|---|---|
Is there a Numpy function to return the first index of something in an array? | 432,112 | <p>I know there is a method for python list to return the first index of something</p>
<pre><code>l = list(1,2,3)
l.index(2)
>>> 1
</code></pre>
<p>Is there something like that for numpy arrays?</p>
| 190 | 2009-01-11T01:21:39Z | 432,325 | <p>If you're going to use this as an index into something else, you can use boolean indices if the arrays are broadcastable; you don't need explicit indices. The absolute simplest way to do this is to simply index based on a truth value.</p>
<pre><code>other_array[first_array == item]
</code></pre>
<p>Any boolean op... | 8 | 2009-01-11T03:52:49Z | [
"python",
"arrays",
"numpy"
] |
Is there a Numpy function to return the first index of something in an array? | 432,112 | <p>I know there is a method for python list to return the first index of something</p>
<pre><code>l = list(1,2,3)
l.index(2)
>>> 1
</code></pre>
<p>Is there something like that for numpy arrays?</p>
| 190 | 2009-01-11T01:21:39Z | 1,044,443 | <p>If you need the index of the first occurrence of <strong>only one value</strong>, you can use <code>nonzero</code> (or <code>where</code>, which amounts to the same thing in this case):</p>
<pre><code>>>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
>>> nonzero(t == 8)
(array([6, 8, 9]),)
>>>... | 43 | 2009-06-25T15:01:00Z | [
"python",
"arrays",
"numpy"
] |
Is there a Numpy function to return the first index of something in an array? | 432,112 | <p>I know there is a method for python list to return the first index of something</p>
<pre><code>l = list(1,2,3)
l.index(2)
>>> 1
</code></pre>
<p>Is there something like that for numpy arrays?</p>
| 190 | 2009-01-11T01:21:39Z | 23,994,923 | <p>you can also convert a Numpy array to list in the air and get its index .
for example</p>
<pre><code>l = [1,2,3,4,5] #python list
a = numpy.array(l) #numpy array
i = a.tolist().index(2) # i will return index of 2
print i
</code></pre>
<p>Will print 1.</p>
| 11 | 2014-06-02T12:47:58Z | [
"python",
"arrays",
"numpy"
] |
when to delete user's session | 432,115 | <p>I'm writing a webapp that will only be used by authenticated users. Some temporary databases and log files will be created during each user session. I'd like to erase all these temp files when the session is finished. </p>
<p>Obviously, a logout or window close event would be sufficient to close the session, but in... | 1 | 2009-01-11T01:23:55Z | 432,126 | <p>User sessions should have a timeout value and should be closed when the timeout expires or the user logs out. Log out is an obvious time to do this and the time out needs to be there in case the user navigates away from your application without logging out.</p>
| 1 | 2009-01-11T01:28:21Z | [
"python",
"session"
] |
when to delete user's session | 432,115 | <p>I'm writing a webapp that will only be used by authenticated users. Some temporary databases and log files will be created during each user session. I'd like to erase all these temp files when the session is finished. </p>
<p>Obviously, a logout or window close event would be sufficient to close the session, but in... | 1 | 2009-01-11T01:23:55Z | 432,170 | <p>Delete User's Session during:</p>
<p>1) Logout</p>
<p>2) Automatic timeout (the length of the timeout can be set through the web.config)</p>
<p>3) As part of any other routine maintenance methods you already have running by deleting any session information which hasn't been accessed for some defined period of tim... | 0 | 2009-01-11T02:01:18Z | [
"python",
"session"
] |
when to delete user's session | 432,115 | <p>I'm writing a webapp that will only be used by authenticated users. Some temporary databases and log files will be created during each user session. I'd like to erase all these temp files when the session is finished. </p>
<p>Obviously, a logout or window close event would be sufficient to close the session, but in... | 1 | 2009-01-11T01:23:55Z | 432,200 | <p>A cron job to clean up any expired session data in the database is a good thing. Depending on how long your sessions last, and how big your database is, you might want to cleanup more often than once per day. But one cleanup pass per day is usually fine.</p>
| 1 | 2009-01-11T02:16:41Z | [
"python",
"session"
] |
Short Python Code to say "Pick the lower value"? | 432,211 | <p>What I mean is,
I'm looking for really short code that returns the lower value.
for example:</p>
<pre><code>a=[1,2,3,4,5,6,7,8,9,10]
b=[1,2,3,4,5,6,7,8]
len(a) = 10
len(b) = 8
if (fill-this-in):
print(lesser-value)
</code></pre>
<p>And I forgot to add that if b is lower than a, I want b returned - not len(b) ... | 6 | 2009-01-11T02:21:43Z | 432,227 | <p><code>min()</code> should accomplish what you need</p>
<pre><code>print(min(a,b))
</code></pre>
| 3 | 2009-01-11T02:30:30Z | [
"python",
"code-snippets"
] |
Short Python Code to say "Pick the lower value"? | 432,211 | <p>What I mean is,
I'm looking for really short code that returns the lower value.
for example:</p>
<pre><code>a=[1,2,3,4,5,6,7,8,9,10]
b=[1,2,3,4,5,6,7,8]
len(a) = 10
len(b) = 8
if (fill-this-in):
print(lesser-value)
</code></pre>
<p>And I forgot to add that if b is lower than a, I want b returned - not len(b) ... | 6 | 2009-01-11T02:21:43Z | 432,229 | <pre>
print(min(a, b))
</pre>
| 18 | 2009-01-11T02:30:58Z | [
"python",
"code-snippets"
] |
Short Python Code to say "Pick the lower value"? | 432,211 | <p>What I mean is,
I'm looking for really short code that returns the lower value.
for example:</p>
<pre><code>a=[1,2,3,4,5,6,7,8,9,10]
b=[1,2,3,4,5,6,7,8]
len(a) = 10
len(b) = 8
if (fill-this-in):
print(lesser-value)
</code></pre>
<p>And I forgot to add that if b is lower than a, I want b returned - not len(b) ... | 6 | 2009-01-11T02:21:43Z | 432,241 | <p>I don't know Python but for something like this I'd use a ternary operator.</p>
<pre><code>print(length(a) < length(b) ? length(a) : length(b))
</code></pre>
<p>One thing to note about this that if they are equal it will print length(b)</p>
| -3 | 2009-01-11T02:38:50Z | [
"python",
"code-snippets"
] |
Short Python Code to say "Pick the lower value"? | 432,211 | <p>What I mean is,
I'm looking for really short code that returns the lower value.
for example:</p>
<pre><code>a=[1,2,3,4,5,6,7,8,9,10]
b=[1,2,3,4,5,6,7,8]
len(a) = 10
len(b) = 8
if (fill-this-in):
print(lesser-value)
</code></pre>
<p>And I forgot to add that if b is lower than a, I want b returned - not len(b) ... | 6 | 2009-01-11T02:21:43Z | 432,247 | <p>Is the following what you want?</p>
<pre><code>if len(a) < len(b):
print a
else:
print b
</code></pre>
<p>Alternatively, if you want to use the ternary operator like <a href="#432241" rel="nofollow">@Andrew G. Johnson</a>:</p>
<pre><code>print a if len(a) < len(b) else b
</code></pre>
<p>PS. Remem... | 0 | 2009-01-11T02:43:38Z | [
"python",
"code-snippets"
] |
Short Python Code to say "Pick the lower value"? | 432,211 | <p>What I mean is,
I'm looking for really short code that returns the lower value.
for example:</p>
<pre><code>a=[1,2,3,4,5,6,7,8,9,10]
b=[1,2,3,4,5,6,7,8]
len(a) = 10
len(b) = 8
if (fill-this-in):
print(lesser-value)
</code></pre>
<p>And I forgot to add that if b is lower than a, I want b returned - not len(b) ... | 6 | 2009-01-11T02:21:43Z | 432,345 | <p>You're not hugely clear about what you want, so some alternatives. Given the following two lists:</p>
<pre><code>a = [1,2,3,4,5,6,7,8,9,10]
b = [1,2,3,4,5,6,7,8]
</code></pre>
<p>To print the shortest list, you can just do..</p>
<pre><code>>>> print(min(a, b))
[1, 2, 3, 4, 5, 6, 7, 8]
</code></pre>
<p>T... | 25 | 2009-01-11T04:21:26Z | [
"python",
"code-snippets"
] |
Short Python Code to say "Pick the lower value"? | 432,211 | <p>What I mean is,
I'm looking for really short code that returns the lower value.
for example:</p>
<pre><code>a=[1,2,3,4,5,6,7,8,9,10]
b=[1,2,3,4,5,6,7,8]
len(a) = 10
len(b) = 8
if (fill-this-in):
print(lesser-value)
</code></pre>
<p>And I forgot to add that if b is lower than a, I want b returned - not len(b) ... | 6 | 2009-01-11T02:21:43Z | 432,386 | <p>If the length of the list is what makes it lower (not its values), then you actually want:</p>
<pre><code>min(a, b, key=len)
</code></pre>
<p>which is only incidentally equivalent to</p>
<pre><code>min(a, b)
</code></pre>
<p>in the given example.</p>
| 5 | 2009-01-11T04:49:03Z | [
"python",
"code-snippets"
] |
Short Python Code to say "Pick the lower value"? | 432,211 | <p>What I mean is,
I'm looking for really short code that returns the lower value.
for example:</p>
<pre><code>a=[1,2,3,4,5,6,7,8,9,10]
b=[1,2,3,4,5,6,7,8]
len(a) = 10
len(b) = 8
if (fill-this-in):
print(lesser-value)
</code></pre>
<p>And I forgot to add that if b is lower than a, I want b returned - not len(b) ... | 6 | 2009-01-11T02:21:43Z | 441,853 | <p>heads up, <code>min(a, b, key=len)</code> only works in python 2.5 and up I think.</p>
<p>(it's not working on my macbook with python 2.4, but my linux server with 2.5 is fine)</p>
| 1 | 2009-01-14T03:56:06Z | [
"python",
"code-snippets"
] |
SFTP in Python? (platform independent) | 432,385 | <p>I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy:</p>
<pre><code>import ftplib
info= ('someuser', 'password') #hard-coded
def putfile(file, site, dir, user=(), verbose=True):
"""
upload ... | 105 | 2009-01-11T04:48:19Z | 432,391 | <p><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> can help you with what you are doing, check out their documentation, there are plenty of examples. Also it is a mature product with a big developer/user community behind it. </p>
| 3 | 2009-01-11T04:51:32Z | [
"python",
"sftp"
] |
SFTP in Python? (platform independent) | 432,385 | <p>I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy:</p>
<pre><code>import ftplib
info= ('someuser', 'password') #hard-coded
def putfile(file, site, dir, user=(), verbose=True):
"""
upload ... | 105 | 2009-01-11T04:48:19Z | 432,403 | <p><a href="http://www.lag.net/paramiko/">Paramiko</a> supports SFTP. I've used it, and I've used Twisted. Both have their place, but you might find it easier to start with Paramiko.</p>
| 77 | 2009-01-11T05:04:22Z | [
"python",
"sftp"
] |
SFTP in Python? (platform independent) | 432,385 | <p>I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy:</p>
<pre><code>import ftplib
info= ('someuser', 'password') #hard-coded
def putfile(file, site, dir, user=(), verbose=True):
"""
upload ... | 105 | 2009-01-11T04:48:19Z | 432,415 | <p>I'd stick with a <a href="http://www.lag.net/paramiko/" rel="nofollow">pure Python</a> solution, but it's not true that there aren't Windows ssh options. <a href="http://cygwin.com/" rel="nofollow">Cygwin</a> has one, for example, and there are <a href="http://www.google.com/search?client=safari&rls=en-us&q... | 4 | 2009-01-11T05:22:41Z | [
"python",
"sftp"
] |
SFTP in Python? (platform independent) | 432,385 | <p>I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy:</p>
<pre><code>import ftplib
info= ('someuser', 'password') #hard-coded
def putfile(file, site, dir, user=(), verbose=True):
"""
upload ... | 105 | 2009-01-11T04:48:19Z | 1,866,984 | <p>If you want easy and simple, you might also want to look at <a href="http://docs.fabfile.org/0.9.0/">Fabric</a>. It's an automated deployment tool like Ruby's Capistrano, but simpler and ofc ourse for Python. It's build on top of Paramiko.</p>
<p>You might not want to do 'automated deployment' but Fabric would suit... | 12 | 2009-12-08T13:29:52Z | [
"python",
"sftp"
] |
SFTP in Python? (platform independent) | 432,385 | <p>I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy:</p>
<pre><code>import ftplib
info= ('someuser', 'password') #hard-coded
def putfile(file, site, dir, user=(), verbose=True):
"""
upload ... | 105 | 2009-01-11T04:48:19Z | 23,900,341 | <p>You should check out pysftp <a href="https://pypi.python.org/pypi/pysftp">https://pypi.python.org/pypi/pysftp</a> it depends on paramiko, but wraps most common use cases to just a few lines of code.</p>
<pre><code>import pysftp
import sys
path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded
localpath = sys... | 24 | 2014-05-27T23:05:35Z | [
"python",
"sftp"
] |
SFTP in Python? (platform independent) | 432,385 | <p>I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy:</p>
<pre><code>import ftplib
info= ('someuser', 'password') #hard-coded
def putfile(file, site, dir, user=(), verbose=True):
"""
upload ... | 105 | 2009-01-11T04:48:19Z | 24,084,874 | <p>Here is a sample using pysftp and a private key.</p>
<pre><code>import pysftp
def upload_file(file_path):
private_key = "~/.ssh/your-key.pem" # can use password keyword in Connection instead
srv = pysftp.Connection(host="your-host", username="user-name", private_key=private_key)
srv.chdir('/var/web/p... | 1 | 2014-06-06T14:56:58Z | [
"python",
"sftp"
] |
Materials for SICP with python? | 432,637 | <p>I want to try out SICP with Python.</p>
<p>Can any one point to materials (video.article...) that teaches Structure and Interpretation of Computer Programs in <strong>python</strong>.</p>
<p>Currently learning from SICP videos of Abelson, Sussman, and Sussman.</p>
| 5 | 2009-01-11T09:13:48Z | 432,767 | <p>A direct translation of SICP in Python would make no sense - Scheme and Python are way too different. But there are a couple similar books in Python. The first that comes to mind is "thinking like a computer scientist". You'll find more informations about available material here:
<a href="http://www.greenteapress.co... | 9 | 2009-01-11T11:24:17Z | [
"python",
"sicp"
] |
Materials for SICP with python? | 432,637 | <p>I want to try out SICP with Python.</p>
<p>Can any one point to materials (video.article...) that teaches Structure and Interpretation of Computer Programs in <strong>python</strong>.</p>
<p>Currently learning from SICP videos of Abelson, Sussman, and Sussman.</p>
| 5 | 2009-01-11T09:13:48Z | 433,688 | <p>Don't think there is a complete set of materials, <a href="http://www.codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages">this</a> is the best I know.</p>
<p>If you are up to generating the material yourself, a bunch of us plan to work through SICP collectively <a href="http://hn-sicp.pbwiki.com/">... | 7 | 2009-01-11T21:01:50Z | [
"python",
"sicp"
] |
Materials for SICP with python? | 432,637 | <p>I want to try out SICP with Python.</p>
<p>Can any one point to materials (video.article...) that teaches Structure and Interpretation of Computer Programs in <strong>python</strong>.</p>
<p>Currently learning from SICP videos of Abelson, Sussman, and Sussman.</p>
| 5 | 2009-01-11T09:13:48Z | 8,455,580 | <p>I think this would be great for you, <a href="http://www-inst.eecs.berkeley.edu/~cs61a/fa11/61a-python/content/www/index.html">CS61A SICP</a> in Python by berkeley</p>
<p><a href="https://github.com/kroger/sicp-python">sicp-python</a> code at Github</p>
<p>and i'm coding it in Python too <a href="https://github.co... | 5 | 2011-12-10T09:24:50Z | [
"python",
"sicp"
] |
Materials for SICP with python? | 432,637 | <p>I want to try out SICP with Python.</p>
<p>Can any one point to materials (video.article...) that teaches Structure and Interpretation of Computer Programs in <strong>python</strong>.</p>
<p>Currently learning from SICP videos of Abelson, Sussman, and Sussman.</p>
| 5 | 2009-01-11T09:13:48Z | 11,670,928 | <p>here is what you need - <a href="http://www-inst.eecs.berkeley.edu/~cs61a/fa11/61a-python/content/www/index.html" rel="nofollow">http://www-inst.eecs.berkeley.edu/~cs61a/fa11/61a-python/content/www/index.html</a></p>
| 4 | 2012-07-26T13:58:17Z | [
"python",
"sicp"
] |
Materials for SICP with python? | 432,637 | <p>I want to try out SICP with Python.</p>
<p>Can any one point to materials (video.article...) that teaches Structure and Interpretation of Computer Programs in <strong>python</strong>.</p>
<p>Currently learning from SICP videos of Abelson, Sussman, and Sussman.</p>
| 5 | 2009-01-11T09:13:48Z | 38,715,493 | <p>Old question, but thought this might be useful for someone.</p>
<p><a href="http://composingprograms.com/" rel="nofollow">http://composingprograms.com/</a></p>
<blockquote>
<p>In the tradition of SICP, this text focuses on methods for
abstraction, programming paradigms, and techniques for managing the
comple... | 0 | 2016-08-02T08:33:12Z | [
"python",
"sicp"
] |
How can I assign a new class attribute via __dict__ in python? | 432,786 | <p>I want to assign a class attribute via a string object - but how?</p>
<p>Example:</p>
<pre><code>class test(object):
pass
a = test()
test.value = 5
a.value
# -> 5
test.__dict__['value']
# -> 5
# BUT:
attr_name = 'next_value'
test.__dict__[attr_name] = 10
# -> 'dictproxy' object does not support item ... | 30 | 2009-01-11T11:44:17Z | 432,790 | <p>There is a builtin function for this:</p>
<pre><code>setattr(test, attr_name, 10)
</code></pre>
<p>Reference: <a href="http://docs.python.org/library/functions.html#setattr">http://docs.python.org/library/functions.html#setattr</a></p>
<p>Example:</p>
<pre><code>>>> class a(object): pass
>>> a.... | 54 | 2009-01-11T11:47:26Z | [
"python",
"oop",
"class",
"attributes"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 432,844 | <p>You can always use the definition of xor to compute it from other logical operations:</p>
<pre><code>(a and not b) or (not a and b)
</code></pre>
<p>But this is a little too verbose for me, and isn't particularly clear at first glance. Another way to do it is:</p>
<pre><code>bool(a) ^ bool(b)
</code></pre>
<p>Th... | 267 | 2009-01-11T12:35:51Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 432,901 | <ul>
<li>Python logical <code>or</code>: <code>A or B</code>: returns <code>A</code> if <code>bool(A)</code> is <code>True</code>, otherwise returns <code>B</code></li>
<li>Python logical <code>and</code>: <code>A and B</code>: returns <code>A</code> if <code>bool(A)</code> is <code>False</code>, otherwise returns <cod... | 15 | 2009-01-11T13:10:52Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 432,940 | <p>Exclusive Or is defined as follows</p>
<pre><code>def xor( a, b ):
return (a or b) and not (a and b)
</code></pre>
| 3 | 2009-01-11T13:39:48Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 432,948 | <p>As <a href="http://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python#432844">Zach</a> explained, you can use:</p>
<pre><code>xor = bool(a) ^ bool(b)
</code></pre>
<p>Personally, I favor a slightly different dialect:</p>
<pre><code>xor = bool(a) + bool(b) == 1
</code></pr... | 20 | 2009-01-11T13:44:31Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 433,091 | <p>How about this?</p>
<pre><code>(not b and a) or (not a and b)
</code></pre>
<p>will give <code>a</code> if <code>b</code> is false<br />
will give <code>b</code> if <code>a</code> is false<br />
will give <code>False</code> otherwise</p>
<p>Or with the Python 2.5+ ternary expression:</p>
<pre><code>(False if a e... | 4 | 2009-01-11T15:29:44Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 433,161 | <p>If you're already normalizing the inputs to booleans, then != is xor.</p>
<pre><code>bool(a) != bool(b)
</code></pre>
| 694 | 2009-01-11T16:30:46Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 1,081,836 | <p>Some of the implementations suggested here will cause repeated evaluation of the operands in some cases, which may lead to unintended side effects and therefore must be avoided.</p>
<p>That said, a <code>xor</code> implementation that returns either <code>True</code> or <code>False</code> is fairly simple; one tha... | 2 | 2009-07-04T09:01:16Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 2,675,401 | <p>As I don't see the simple variant of xor using variable arguments and only operation on Truth values True or False, I'll just throw it here for anyone to use.
It's as noted by others, pretty (not to say very) straightforward.</p>
<pre><code>def xor(*vars):
sum = bool(False)
for v in vars:
sum = sum ... | 5 | 2010-04-20T13:21:43Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 4,957,708 | <p>It's easy when you know what XOR does:</p>
<pre><code>def logical_xor(a, b):
return (a and not b) or (not a and b)
test_data = [
[False, False],
[False, True],
[True, False],
[True, True],
]
for a, b in test_data:
print '%r xor %s = %r' % (a, b, logical_xor(a, b))
</code></pre>
| 3 | 2011-02-10T13:34:36Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 8,787,948 | <p>XOR is implemented in <code>operator.xor</code>.</p>
| 2 | 2012-01-09T11:49:00Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 11,036,506 | <p>Exclusive-or is already built-in to Python, in the <a href="http://docs.python.org/library/operator.html#operator.xor"><code>operator</code></a> module:</p>
<pre class="lang-py prettyprint-override"><code>from operator import xor
xor(bool(a), bool(b))
</code></pre>
| 85 | 2012-06-14T15:34:09Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 22,265,366 | <p>Sometimes I find myself working with 1 and 0 instead of boolean True and False values. In this case xor can be defined as </p>
<pre><code>z = (x + y) % 2
</code></pre>
<p>which has the following truth table:</p>
<pre><code> x
|0|1|
-+-+-+
0|0|1|
y -+-+-+
1|1|0|
-+-+-+
</code></pre>
| 2 | 2014-03-08T05:11:44Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 29,514,257 | <p>This gets the logical exclusive XOR for two (or more) variables</p>
<pre><code>str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
any([str1, str2]) and not all([str1, str2])
</code></pre>
<p>The first problem with this setup is that it most likely traverses the whole list twice and, at a ... | 1 | 2015-04-08T12:11:48Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 35,198,876 | <p>I've tested several approaches and <code>not a != (not b)</code> appeared to be the fastest.</p>
<p>Here are some tests</p>
<pre><code>%timeit not a != (not b)
10000000 loops, best of 3: 78.5 ns per loop
In [130]: %timeit bool(a) != bool(b)
1000000 loops, best of 3: 343 ns per loop
In [131]: %timeit not a ^ (not... | 4 | 2016-02-04T10:42:56Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 37,337,925 | <p>Rewarding thread:</p>
<p>Anoder idea... Just you try the (may be) pythonic expression «is not» in order to get behavior of logical «xor»</p>
<p>The truth table would be:</p>
<pre><code>>>> True is not True
False
>>> True is not False
True
>>> False is not True
True
>>> Fals... | 1 | 2016-05-20T04:25:11Z | [
"python",
"logic"
] |
How do you get the logical xor of two variables in Python? | 432,842 | <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or">logical xor</a> of two variables in Python?</p>
<p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p>
<pre><code>str1 = raw_input("Ent... | 310 | 2009-01-11T12:34:43Z | 38,708,774 | <p>I know this is late, but I had a thought and it might be worth, just for documentation. Perhaps this would work:<code>np.abs(x-y)</code> The idea is that </p>
<ol>
<li>if x=True=1 and y=False=0 then the result would be |1-0|=1=True</li>
<li>if x=False=0 and y=False=0 then the result would be |0-0|=0=False</li>
<li>... | 1 | 2016-08-01T21:57:05Z | [
"python",
"logic"
] |
How do I add a custom inline admin widget in Django? | 433,251 | <p>This is easy for non-inlines. Just override the following in the your admin.py AdminOptions:</p>
<pre><code>def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'photo':
kwargs['widget'] = AdminImageWidget()
return db_field.formfield(**kwargs)
return super(NewsOptions,sel... | 10 | 2009-01-11T17:25:11Z | 434,129 | <p>It works exactly the same way. The TabularInline and StackedInline classes also have a formfield_for_dbfield method, and you override it the same way in your subclass.</p>
| 8 | 2009-01-12T00:44:41Z | [
"python",
"django",
"django-admin"
] |
How do I add a custom inline admin widget in Django? | 433,251 | <p>This is easy for non-inlines. Just override the following in the your admin.py AdminOptions:</p>
<pre><code>def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'photo':
kwargs['widget'] = AdminImageWidget()
return db_field.formfield(**kwargs)
return super(NewsOptions,sel... | 10 | 2009-01-11T17:25:11Z | 810,970 | <p>Edit: Nevermind. This was just a stupid error on my part.</p>
<p>Could you possibly provide a small snippet of this working in inlines? When I try the code below I'm just getting some weird keyerror.</p>
<pre><code>class PictureInline(admin.StackedInline):
model = Picture_Gallery
extra = 3
def formfiel... | 1 | 2009-05-01T10:52:42Z | [
"python",
"django",
"django-admin"
] |
How do I add a custom inline admin widget in Django? | 433,251 | <p>This is easy for non-inlines. Just override the following in the your admin.py AdminOptions:</p>
<pre><code>def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'photo':
kwargs['widget'] = AdminImageWidget()
return db_field.formfield(**kwargs)
return super(NewsOptions,sel... | 10 | 2009-01-11T17:25:11Z | 2,908,321 | <p>Since Django 1.1, formfield_overrides is also working</p>
<pre><code>formfield_overrides = {
models.ImageField: {'widget': AdminImageWidget},
}
</code></pre>
| 6 | 2010-05-25T20:35:09Z | [
"python",
"django",
"django-admin"
] |
Column comparison in Django queries | 433,294 | <p>I have a following model:</p>
<pre><code>class Car(models.Model):
make = models.CharField(max_length=40)
mileage_limit = models.IntegerField()
mileage = models.IntegerField()
</code></pre>
<p>I want to select all cars where mileage is less than mileage_limit, so in SQL it would be something like:</p>
... | 12 | 2009-01-11T17:47:51Z | 433,321 | <p>You can't do this right now without custom SQL. The django devs are working on an F() function that would make it possible: <a href="http://groups.google.com/group/django-developers/browse_thread/thread/c8cff7e5e16c692a#" rel="nofollow">#7210 - F() syntax, design feedback required.</a></p>
| 8 | 2009-01-11T18:00:30Z | [
"python",
"django",
"orm"
] |
Python Library to Generate VCF Files? | 433,331 | <p>Know of any good libraries for this? I did some searches and didn't come across anything. Someone somewhere must have done this before, I hate to reinvent the wheel.</p>
| 6 | 2009-01-11T18:05:15Z | 433,408 | <p>PyCoCuMa appears to have a VCF parser built into it, and it'll generate VCard output. You might have some luck with it. I played around with it a bit; it parsed some VCF files I have lying around without any problems. You'll most likely have to poke through the source to figure out how to use it, though.</p>
<p>See... | 2 | 2009-01-11T18:45:43Z | [
"python",
"vcf"
] |
Python Library to Generate VCF Files? | 433,331 | <p>Know of any good libraries for this? I did some searches and didn't come across anything. Someone somewhere must have done this before, I hate to reinvent the wheel.</p>
| 6 | 2009-01-11T18:05:15Z | 433,453 | <p>I would look at:</p>
<p><a href="http://vobject.skyhouseconsulting.com/">http://vobject.skyhouseconsulting.com/usage.html</a> (look under "Usage examples")</p>
<p>Very easy parsing and generation of both vCal and vCard.</p>
| 7 | 2009-01-11T19:13:17Z | [
"python",
"vcf"
] |
Python-Regex, what's going on here? | 433,388 | <p>I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)?</p>
<pre><code>>>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)'
>>>... | 6 | 2009-01-11T18:36:21Z | 433,416 | <p>The <strong>search</strong> method will return an object containing the results of your regex pattern. </p>
<p><strong>groupdict</strong> returns a dictionnary of groups where the keys are the name of the groups defined by (?P...). Here <em>name</em> is a name for the group.</p>
<p><strong>group</strong> returns a... | 2 | 2009-01-11T18:52:39Z | [
"python",
"regex"
] |
Python-Regex, what's going on here? | 433,388 | <p>I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)?</p>
<pre><code>>>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)'
>>>... | 6 | 2009-01-11T18:36:21Z | 433,418 | <p>regex definition:</p>
<pre><code>(?P<zip>...)
</code></pre>
<p>Creates a named group "zip"</p>
<pre><code>Zip:\s*
</code></pre>
<p>Match "Zip:" and zero or more whitespace characters</p>
<pre><code>\d
</code></pre>
<p>Match a digit</p>
<pre><code>\w
</code></pre>
<p>Match a word character [A-Za-z0-9_]<... | 8 | 2009-01-11T18:54:18Z | [
"python",
"regex"
] |
Python-Regex, what's going on here? | 433,388 | <p>I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)?</p>
<pre><code>>>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)'
>>>... | 6 | 2009-01-11T18:36:21Z | 433,420 | <p>The <code>(?P<identifier>match)</code> syntax is Python's way of implementing named capturing groups. That way, you can access what was matched by <code>match</code> using a name instead of just a sequential number.</p>
<p>Since the first set of parentheses is named <code>zip</code>, you can access its match ... | 0 | 2009-01-11T18:55:32Z | [
"python",
"regex"
] |
Python-Regex, what's going on here? | 433,388 | <p>I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)?</p>
<pre><code>>>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)'
>>>... | 6 | 2009-01-11T18:36:21Z | 433,423 | <pre><code># my_regex = r' <= this means that the string is a raw string, normally you'd need to use double backslashes
# ( ... ) this groups something
# ? this means that the previous bit was optional, why it's just after a group bracket I know not
# * this means "as many of as you can find"
# \s is whitespace
# \d... | 1 | 2009-01-11T18:57:17Z | [
"python",
"regex"
] |
Python-Regex, what's going on here? | 433,388 | <p>I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)?</p>
<pre><code>>>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)'
>>>... | 6 | 2009-01-11T18:36:21Z | 433,430 | <p>Adding to previous answers: In my opinion you'd better choose one type of groups (named or unnamed) and stick with it. Normally I use named groups. For example: </p>
<pre><code>>>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(?P<state>State:\s*\w\w)'
>>> addrs = "Zip: 10010 State: NY"
&g... | 0 | 2009-01-11T19:00:33Z | [
"python",
"regex"
] |
Python-Regex, what's going on here? | 433,388 | <p>I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)?</p>
<pre><code>>>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)'
>>>... | 6 | 2009-01-11T18:36:21Z | 436,457 | <p><a href="http://strfrield.com/" rel="nofollow">strfriend is <em>your</em> friend:</p>
<p>http://strfriend.com/vis?re=(Zip%3A\s*\d\d\d\d\d)\s*(State%3A\s*\w\w)</a></p>
<p><strong>EDIT:</strong> Why the heck is it making the entire line a link in the actual comment, but not the preview?</p>
| 0 | 2009-01-12T18:28:12Z | [
"python",
"regex"
] |
Filtering a complete date in django? | 433,507 | <p>There are several filter methods for dates (year,month,day). If I want to match a full date, say 2008/10/18, is there a better way than this:</p>
<pre><code>Entry.objects.filter(pub_date__year=2008).filter(pub_date__month=10).filter(pub_date__day=18)
</code></pre>
| 0 | 2009-01-11T19:42:06Z | 433,519 | <p>How about using a <a href="http://docs.python.org/library/datetime.html#datetime-objects">datetime</a> object. For example:</p>
<pre><code>from datetime import datetime
Entry.objects.filter(pub_date=datetime(2008, 10, 18))
</code></pre>
| 10 | 2009-01-11T19:47:24Z | [
"python",
"django",
"filter",
"date",
"django-queryset"
] |
Is late binding consistent with the philosophy of "readibility counts"? | 433,662 | <p>I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had the chance to read Django's code, and have started wondering if Python rea... | 1 | 2009-01-11T20:47:04Z | 433,675 | <p>If what the code is doing becomes mysterious for some reason .. there should either be comments or the function names should make it obvious.</p>
<p>This is just my opinion though.</p>
| 2 | 2009-01-11T20:53:15Z | [
"python",
"readability"
] |
Is late binding consistent with the philosophy of "readibility counts"? | 433,662 | <p>I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had the chance to read Django's code, and have started wondering if Python rea... | 1 | 2009-01-11T20:47:04Z | 433,684 | <p>I personally think not having to declare variables is one of the dangerous things in Python, especially when doing classes. It is all too easy to accidentally create a variable by simple mistyping and then boggle at the code at length, unable to find the mistake.</p>
| 2 | 2009-01-11T21:00:05Z | [
"python",
"readability"
] |
Is late binding consistent with the philosophy of "readibility counts"? | 433,662 | <p>I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had the chance to read Django's code, and have started wondering if Python rea... | 1 | 2009-01-11T20:47:04Z | 433,699 | <p>Adding a property just before you need it will prevent you from using it before it's got a value. Personally, I <em>always</em> find classes hard to follow just from reading source - I read the documentation and find out what it's supposed to do, and then it usually makes sense when I read the source again.</p>
| 2 | 2009-01-11T21:05:20Z | [
"python",
"readability"
] |
Is late binding consistent with the philosophy of "readibility counts"? | 433,662 | <p>I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had the chance to read Django's code, and have started wondering if Python rea... | 1 | 2009-01-11T20:47:04Z | 433,731 | <p>A sufficiently talented miscreant can write unreadable code in any language. Python attempts to impose some rules on structure and naming to nudge coders in the right direction, but there's no way to force such a thing.</p>
<p>For what it's worth, I try to limit the scope of local variables to the area where they'r... | 5 | 2009-01-11T21:20:38Z | [
"python",
"readability"
] |
Is late binding consistent with the philosophy of "readibility counts"? | 433,662 | <p>I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had the chance to read Django's code, and have started wondering if Python rea... | 1 | 2009-01-11T20:47:04Z | 433,736 | <p>The code fragment you present is fairly atypical (which might also because you probably made it up):</p>
<ul>
<li><p>you wouldn't normally have an instance variable (self.c) that is a floating point number at some point, and a string at a different point. It should be either a number or a string all the time.</p></... | 14 | 2009-01-11T21:21:42Z | [
"python",
"readability"
] |
Is late binding consistent with the philosophy of "readibility counts"? | 433,662 | <p>I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had the chance to read Django's code, and have started wondering if Python rea... | 1 | 2009-01-11T20:47:04Z | 433,748 | <p>I agree that what you have seen can be confusing and ought to be accompanied by documentation. But confusing things can happen in any language.</p>
<p>In your own code, you should apply whatever conventions make things easiest for you to maintain the code. With respect to this particular issue, there are a number o... | 3 | 2009-01-11T21:24:50Z | [
"python",
"readability"
] |
Is late binding consistent with the philosophy of "readibility counts"? | 433,662 | <p>I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had the chance to read Django's code, and have started wondering if Python rea... | 1 | 2009-01-11T20:47:04Z | 433,775 | <p>This problem is easily solved by specifying coding standards such as declaring all instance variables in the <strong>init</strong> method of your object. This isn't really a problem with python as much as the programmer.</p>
| 3 | 2009-01-11T21:39:50Z | [
"python",
"readability"
] |
Is late binding consistent with the philosophy of "readibility counts"? | 433,662 | <p>I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had the chance to read Django's code, and have started wondering if Python rea... | 1 | 2009-01-11T20:47:04Z | 433,821 | <p>The fact that such stuff is allowed is only useful in rare times for prototyping; while Javascript tends to allow anything and maybe such an example could be considered normal (I don't really know), in Python this is mostly a negative byproduct of omission of type declaration, which can help speeding up development ... | 0 | 2009-01-11T22:05:35Z | [
"python",
"readability"
] |
Analyse python list with algorithm for counting occurences over date ranges | 433,669 | <p>The following shows the structure of some data I have (format: a list of lists)</p>
<pre><code>data =
[
[1,2008-12-01],
[1,2008-12-01],
[2,2008-12-01]
... (the lists continue)
]
</code></pre>
<p>The dates range from 2008-12-01 to 2008-12-25.</p>
<p>The first field identifies a user by id, the second fie... | 2 | 2009-01-11T20:49:16Z | 433,679 | <p>Your result is a dictionary, right?</p>
<pre><code>{ userNumber: setOfDays }
</code></pre>
<p>How about this to get started.</p>
<pre><code>from collections import defaultdict
visits = defaultdict(set)
for user, date in someList:
visits[user].add(date)
</code></pre>
<p>This gives you a dictionary with a set ... | 4 | 2009-01-11T20:56:29Z | [
"python",
"algorithm"
] |
Analyse python list with algorithm for counting occurences over date ranges | 433,669 | <p>The following shows the structure of some data I have (format: a list of lists)</p>
<pre><code>data =
[
[1,2008-12-01],
[1,2008-12-01],
[2,2008-12-01]
... (the lists continue)
]
</code></pre>
<p>The dates range from 2008-12-01 to 2008-12-25.</p>
<p>The first field identifies a user by id, the second fie... | 2 | 2009-01-11T20:49:16Z | 433,713 | <p>First, I should mention that you NEED to store the date as a string. Currently, it would do arithmetic on your current entry. So, if you format <code>data</code> like this, it will work better:</p>
<pre><code>data =
[
[1,"2008-12-01"],
[1,"2008-12-01"],
[2,"2008-12-01"]
]
</code></pre>
<p>Next, we can do s... | 0 | 2009-01-11T21:11:42Z | [
"python",
"algorithm"
] |
Analyse python list with algorithm for counting occurences over date ranges | 433,669 | <p>The following shows the structure of some data I have (format: a list of lists)</p>
<pre><code>data =
[
[1,2008-12-01],
[1,2008-12-01],
[2,2008-12-01]
... (the lists continue)
]
</code></pre>
<p>The dates range from 2008-12-01 to 2008-12-25.</p>
<p>The first field identifies a user by id, the second fie... | 2 | 2009-01-11T20:49:16Z | 434,034 | <p>It is unclear what exactly your requirement are. Here's my take:</p>
<pre><code>#!/usr/bin/env python
from collections import defaultdict
data = [
[1,'2008-12-01'],
[3,'2008-12-25'],
[1,'2008-12-01'],
[2,'2008-12-01'],
]
d = defaultdict(set)
for id, day in data:
d[day].add(id)
for day in sorted(d):
... | 0 | 2009-01-11T23:39:10Z | [
"python",
"algorithm"
] |
Analyse python list with algorithm for counting occurences over date ranges | 433,669 | <p>The following shows the structure of some data I have (format: a list of lists)</p>
<pre><code>data =
[
[1,2008-12-01],
[1,2008-12-01],
[2,2008-12-01]
... (the lists continue)
]
</code></pre>
<p>The dates range from 2008-12-01 to 2008-12-25.</p>
<p>The first field identifies a user by id, the second fie... | 2 | 2009-01-11T20:49:16Z | 434,337 | <p>How about this: this gives you set of days as well as count:</p>
<pre><code>In [39]: from itertools import groupby ##itertools is a part of the standard library.
In [40]: l=[[1, '2008-12-01'],
....: [1, '2008-12-01'],
....: [2, '2008-12-01'],
....: [1, '2008-12-01'],
....: [3, '3008-12-04']]
In [4... | 0 | 2009-01-12T03:13:49Z | [
"python",
"algorithm"
] |
Analyse python list with algorithm for counting occurences over date ranges | 433,669 | <p>The following shows the structure of some data I have (format: a list of lists)</p>
<pre><code>data =
[
[1,2008-12-01],
[1,2008-12-01],
[2,2008-12-01]
... (the lists continue)
]
</code></pre>
<p>The dates range from 2008-12-01 to 2008-12-25.</p>
<p>The first field identifies a user by id, the second fie... | 2 | 2009-01-11T20:49:16Z | 434,346 | <p>Rewriting S.Lott's answer in SQL as an exercise, just to check that I got the requirements right...</p>
<pre><code>SELECT * FROM someList;
userid | date
--------+------------
1 | 2008-12-01
1 | 2008-12-02
1 | 2008-12-03
1 | 2008-12-04
1 | 2008-12-05
2 | 2008-12-03
... | 1 | 2009-01-12T03:18:18Z | [
"python",
"algorithm"
] |
Analyse python list with algorithm for counting occurences over date ranges | 433,669 | <p>The following shows the structure of some data I have (format: a list of lists)</p>
<pre><code>data =
[
[1,2008-12-01],
[1,2008-12-01],
[2,2008-12-01]
... (the lists continue)
]
</code></pre>
<p>The dates range from 2008-12-01 to 2008-12-25.</p>
<p>The first field identifies a user by id, the second fie... | 2 | 2009-01-11T20:49:16Z | 435,096 | <p>This is probably not the most pythonic or efficient or smartest or whatever way of doing this. But maybe you can confirm if I've understood the requirements correctly:</p>
<pre><code>>>> log=[[1, '2008-12-01'], [1, '2008-12-01'],[2, '2008-12-01'],[2, '2008-12-03'], [1, '2008-12-04'], [3, '2008-12-04'], [4,... | 1 | 2009-01-12T10:59:06Z | [
"python",
"algorithm"
] |
Shorthand adding/appending in Python | 433,795 | <p>I like that in PHP I can do the following</p>
<pre><code>$myInteger++;
$myString += 'more text';
</code></pre>
<p>With Python I must do the following</p>
<pre><code>myInteger = myInteger + 1
myString = myString + "more text"
</code></pre>
<p>Is there a better way to add or append to a variable in Python?</p>
| 7 | 2009-01-11T21:52:29Z | 433,803 | <p>Python doesn't have the increment (++) and decrement (--) operators, but it does have the += operator (and -=, etc.) so you can do this:</p>
<pre><code>myInteger += 1
myString += "more text"
</code></pre>
| 21 | 2009-01-11T21:54:52Z | [
"python"
] |
Shorthand adding/appending in Python | 433,795 | <p>I like that in PHP I can do the following</p>
<pre><code>$myInteger++;
$myString += 'more text';
</code></pre>
<p>With Python I must do the following</p>
<pre><code>myInteger = myInteger + 1
myString = myString + "more text"
</code></pre>
<p>Is there a better way to add or append to a variable in Python?</p>
| 7 | 2009-01-11T21:52:29Z | 433,804 | <p>You could do it in the same way you are doing it in PHP:</p>
<pre><code>var += 1
</code></pre>
<p>But my advice is to write it down clear:</p>
<pre><code>var = var + 1
</code></pre>
| 0 | 2009-01-11T21:55:35Z | [
"python"
] |
JFileChooser for Python? | 433,945 | <p>I was wondering if there is something similar to Java's <code>JFileChooser</code> for Python?</p>
<p><code>JFileChooser</code> is a graphical front end to choose a file.</p>
<p>Preferably something that is already with Python. Maybe with Tkinter.</p>
| 3 | 2009-01-11T23:03:34Z | 433,964 | <p>That would depend on your windowing toolkit. wxWidgets provides the <a href="http://docs.wxwidgets.org/stable/wx_wxfiledialog.html" rel="nofollow">wxFileDialog</a>.</p>
| 1 | 2009-01-11T23:11:53Z | [
"java",
"python",
"jfilechooser"
] |
JFileChooser for Python? | 433,945 | <p>I was wondering if there is something similar to Java's <code>JFileChooser</code> for Python?</p>
<p><code>JFileChooser</code> is a graphical front end to choose a file.</p>
<p>Preferably something that is already with Python. Maybe with Tkinter.</p>
| 3 | 2009-01-11T23:03:34Z | 433,967 | <p>wxPython (www.wxpython.org) provides the wx.FileDialog class which will give you a native file selection dialog on any of the supported platforms (Mac, Linux or Windows).</p>
| 4 | 2009-01-11T23:12:59Z | [
"java",
"python",
"jfilechooser"
] |
JFileChooser for Python? | 433,945 | <p>I was wondering if there is something similar to Java's <code>JFileChooser</code> for Python?</p>
<p><code>JFileChooser</code> is a graphical front end to choose a file.</p>
<p>Preferably something that is already with Python. Maybe with Tkinter.</p>
| 3 | 2009-01-11T23:03:34Z | 433,977 | <p>Maybe you would like to take a look at Jython.</p>
| 0 | 2009-01-11T23:16:43Z | [
"java",
"python",
"jfilechooser"
] |
JFileChooser for Python? | 433,945 | <p>I was wondering if there is something similar to Java's <code>JFileChooser</code> for Python?</p>
<p><code>JFileChooser</code> is a graphical front end to choose a file.</p>
<p>Preferably something that is already with Python. Maybe with Tkinter.</p>
| 3 | 2009-01-11T23:03:34Z | 434,009 | <p>Easiest way I ever found to do this (using PyGTK and <a href="http://async.com.br/projects/kiwi" rel="nofollow">Kiwi</a>):</p>
<pre><code>from kiwi.ui.dialogs import open as open_dialog
chosen_path = open_dialog('Select a file', folder='/start/folder')
if chosen_path is not None:
# do something ...
</code></p... | 3 | 2009-01-11T23:29:26Z | [
"java",
"python",
"jfilechooser"
] |
JFileChooser for Python? | 433,945 | <p>I was wondering if there is something similar to Java's <code>JFileChooser</code> for Python?</p>
<p><code>JFileChooser</code> is a graphical front end to choose a file.</p>
<p>Preferably something that is already with Python. Maybe with Tkinter.</p>
| 3 | 2009-01-11T23:03:34Z | 434,610 | <p>For something that doesn't require wxPython and sticks with the standard Python libs, you can use the tkFileDialog.askopenfilename() method: </p>
<pre><code>#!/usr/bin/python
from Tkinter import *
from tkFileDialog import askopenfilename
root = Tk()
root.withdraw()
print askopenfilename()
</code></pre>
| 3 | 2009-01-12T06:29:00Z | [
"java",
"python",
"jfilechooser"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 434,303 | <p>There doesn't seem to be a pretty way to do this. <a href="http://code.activestate.com/recipes/425397/" rel="nofollow">Here</a> is a page that has a number of methods, including:</p>
<pre><code>def split_seq(seq, size):
newseq = []
splitsize = 1.0/size*len(seq)
for i in range(size):
newseq.appe... | 0 | 2009-01-12T02:56:54Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 434,307 | <p>In your second method, I would advance to the next group of 4 by doing this:</p>
<pre><code>ints = ints[4:]
</code></pre>
<p>However, I haven't done any performance measurement so I don't know which one might be more efficient.</p>
<p>Having said that, I would usually choose the first method. It's not pretty, but... | 1 | 2009-01-12T02:59:16Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 434,314 | <pre><code>import itertools
def chunks(iterable,size):
it = iter(iterable)
chunk = tuple(itertools.islice(it,size))
while chunk:
yield chunk
chunk = tuple(itertools.islice(it,size))
# though this will throw ValueError if the length of ints
# isn't a multiple of four:
for x1,x2,x3,x4 in chun... | 15 | 2009-01-12T03:02:59Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 434,321 | <p>I'm a fan of </p>
<pre><code>chunkSize= 4
for i in xrange(0, len(ints), chunkSize):
chunk = ints[i:i+chunkSize]
# process chunk of size <= chunkSize
</code></pre>
| 44 | 2009-01-12T03:06:09Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 434,328 | <pre><code>def chunker(seq, size):
return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
</code></pre>
<p>Simple. Easy. Fast. Works with any sequence:</p>
<pre><code>text = "I am a very, very helpful text"
for group in chunker(text, 7):
print repr(group),
# 'I am a ' 'very, v' 'ery hel' 'pful te' ... | 233 | 2009-01-12T03:10:17Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 434,349 | <p>If the list is large, the highest-performing way to do this will be to use a generator:</p>
<pre><code>def get_chunk(iterable, chunk_size):
result = []
for item in iterable:
result.append(item)
if len(result) == chunk_size:
yield tuple(result)
result = []
if len(r... | 2 | 2009-01-12T03:19:30Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 434,382 | <p>If the lists are the same size, you can combine them into lists of 4-tuples with <code>zip()</code>. For example:</p>
<pre><code># Four lists of four elements each.
l1 = range(0, 4)
l2 = range(4, 8)
l3 = range(8, 12)
l4 = range(12, 16)
for i1, i2, i3, i4 in zip(l1, l2, l3, l4):
...
</code></pre>
<p>Here's wh... | 0 | 2009-01-12T03:46:12Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 434,398 | <pre><code>from itertools import izip_longest
def chunker(iterable, chunksize, filler):
return izip_longest(*[iter(iterable)]*chunksize, fillvalue=filler)
</code></pre>
| 10 | 2009-01-12T03:56:20Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 434,411 | <p>Modified from the <a href="http://docs.python.org/library/itertools.html#recipes">recipes</a> section of Python's <a href="http://docs.python.org/library/itertools.html">itertools</a> docs:</p>
<pre><code>from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
... | 174 | 2009-01-12T04:07:20Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 435,712 | <p>Since nobody's mentioned it yet here's a <code>zip()</code> solution:</p>
<pre><code>>>> def chunker(iterable, chunksize):
... return zip(*[iter(iterable)]*chunksize)
</code></pre>
<p>It works only if your sequence's length is always divisible by the chunk size or you don't care about a trailing chunk... | 3 | 2009-01-12T15:13:41Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 8,312,908 | <p>Posting this as an answer since I cannot comment...</p>
<p>Using map() instead of zip() fixes the padding issue in J.F. Sebastian's answer:</p>
<pre><code>>>> def chunker(iterable, chunksize):
... return map(None,*[iter(iterable)]*chunksize)
</code></pre>
<p>Example:</p>
<pre><code>>>> s = '1... | 6 | 2011-11-29T14:58:00Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 10,791,887 | <p>The ideal solution for this problem works with iterators (not just sequences). It should also be fast.</p>
<p>This is the solution provided by the documentation for itertools:</p>
<pre><code>def grouper(n, iterable, fillvalue=None):
#"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] *... | 1 | 2012-05-29T00:50:20Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 13,335,525 | <p>Yet another answer, the advantages of which are:</p>
<p>1) Easily understandable<br>
2) Works on any iterable, not just sequences (some of the above answers will choke on filehandles)<br>
3) Does not load the chunk into memory all at once<br>
4) Does not make a chunk-long list of references to the same iterator in ... | 1 | 2012-11-11T21:14:55Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 13,735,775 | <p>Similar to other proposals, but not exactly identical, I like doing it this way, because it's simple and easy to read:</p>
<pre><code>it = iter([1, 2, 3, 4, 5, 6, 7, 8, 9])
for chunk in zip(it, it, it, it):
print chunk
>>> (1, 2, 3, 4)
>>> (5, 6, 7, 8)
</code></pre>
<p>This way you won't get... | 5 | 2012-12-06T01:56:30Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 15,000,147 | <p>Using little functions and things really doesn't appeal to me; I prefer to just use slices:</p>
<pre><code>data = [...]
chunk_size = 10000 # or whatever
chunks = [data[i:i+chunk_size] for i in xrange(0,len(data),chunk_size)]
for chunk in chunks:
...
</code></pre>
| 3 | 2013-02-21T10:40:10Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 18,243,990 | <p>I needed a solution that would also work with sets and generators. I couldn't come up with anything very short and pretty, but it's quite readable at least.</p>
<pre><code>def chunker(seq, size):
res = []
for el in seq:
res.append(el)
if len(res) == size:
yield res
re... | 5 | 2013-08-14T23:24:51Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 21,906,814 | <pre><code>def group_by(iterable, size):
"""Group an iterable into lists that don't exceed the size given.
>>> group_by([1,2,3,4,5], 2)
[[1, 2], [3, 4], [5]]
"""
sublist = []
for index, item in enumerate(iterable):
if index > 0 and index % size == 0:
yield subl... | 1 | 2014-02-20T11:45:37Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 22,049,333 | <p>Another approach would be to use the two-argument form of <code>iter</code>: </p>
<pre><code>from itertools import islice
def group(it, size):
it = iter(it)
return iter(lambda: tuple(islice(it, size)), ())
</code></pre>
<p>This can be adapted easily to use padding (this is similar to <a href="http://stack... | 1 | 2014-02-26T17:52:46Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 24,046,729 | <p>You can use <a href="http://funcy.readthedocs.org/en/latest/seqs.html#partition" rel="nofollow">partition</a> or <a href="http://funcy.readthedocs.org/en/latest/seqs.html#chunks" rel="nofollow">chunks</a> function from <a href="https://github.com/Suor/funcy" rel="nofollow">funcy</a> library:</p>
<pre><code>from fun... | 0 | 2014-06-04T20:13:23Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 25,606,173 | <p>One-liner, adhoc solution to iterate over a list <code>x</code> in chunks of size <code>4</code> -</p>
<pre><code>for a, b, c, d in zip(x[0::4], x[1::4], x[2::4], x[3::4]):
... do something with a, b, c and d ...
</code></pre>
| 0 | 2014-09-01T12:44:40Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 26,437,863 | <p>To avoid all conversions to a list <code>import itertools</code> and:</p>
<pre><code>>>> for k, g in itertools.groupby(xrange(35), lambda x: x/10):
... list(g)
</code></pre>
<p>Produces:</p>
<pre><code>...
0 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
2 [20, 21, 22, 23,... | 1 | 2014-10-18T08:42:28Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 27,008,789 | <p>With NumPy it's simple:</p>
<pre><code>ints = array([1, 2, 3, 4, 5, 6, 7, 8])
for int1, int2 in ints.reshape(-1, 2):
print(int1, int2)
</code></pre>
<p>output:</p>
<pre><code>1 2
3 4
5 6
7 8
</code></pre>
| 0 | 2014-11-19T04:09:38Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 27,144,240 | <p>At first, I designed it to split strings into substrings to parse string containing hex.<br>
Today I turned it into complex, but still simple generator.</p>
<pre><code>def chunker(iterable, size, reductor, condition):
it = iter(iterable)
def chunk_generator():
return (next(it) for _ in range(size))
... | 0 | 2014-11-26T08:21:04Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 27,257,438 | <p>About solution gave by <code>J.F. Sebastian</code> <a href="http://stackoverflow.com/a/435712/3821804">here</a>:</p>
<pre><code>def chunker(iterable, chunksize):
return zip(*[iter(iterable)]*chunksize)
</code></pre>
<p>It's clever, but has one disadvantage - always return tuple. How to get string instead?<br>
... | 1 | 2014-12-02T19:32:56Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
What is the most "pythonic" way to iterate over a list in chunks? | 434,287 | <p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p>
<pre><code>for i in xrange(0, len(ints), 4)... | 241 | 2009-01-12T02:48:22Z | 29,568,040 | <p>Here is a chunker without imports that supports generators:</p>
<pre><code>def chunks(seq, size):
it = iter(seq)
while True:
ret = tuple(it.next() for _ in range(size))
if len(ret) == size:
yield ret
else:
raise StopIteration()
</code></pre>
<p>Example of use... | 1 | 2015-04-10T18:07:52Z | [
"python",
"list",
"loops",
"optimization",
"chunks"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.