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) &gt;&gt;&gt; 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 operation works:</p> <pre><code>a = numpy.arange(100) other_array[first_array &gt; 50] </code></pre> <p>The nonzero method takes booleans, too:</p> <pre><code>index = numpy.nonzero(first_array == item)[0][0] </code></pre> <p>The two zeros are for the tuple of indices (assuming first_array is 1D) and then the first item in the array of indices.</p>
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) &gt;&gt;&gt; 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>&gt;&gt;&gt; t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8]) &gt;&gt;&gt; nonzero(t == 8) (array([6, 8, 9]),) &gt;&gt;&gt; nonzero(t == 8)[0][0] 6 </code></pre> <p>If you need the first index of each of <strong>many values</strong>, you could obviously do the same as above repeatedly, but there is a trick that may be faster. The following finds the indices of the first element of each <em>subsequence</em>:</p> <pre><code>&gt;&gt;&gt; nonzero(r_[1, diff(t)[:-1]]) (array([0, 3, 5, 6, 7, 8]),) </code></pre> <p>Notice that it finds the beginning of both subsequence of 3s and both subsequences of 8s:</p> <p>[<strong>1</strong>, 1, 1, <strong>2</strong>, 2, <strong>3</strong>, <strong>8</strong>, <strong>3</strong>, <strong>8</strong>, 8]</p> <p>So it's slightly different than finding the first <em>occurrence</em> of each value. In your program, you may be able to work with a sorted version of <code>t</code> to get what you want:</p> <pre><code>&gt;&gt;&gt; st = sorted(t) &gt;&gt;&gt; nonzero(r_[1, diff(st)[:-1]]) (array([0, 3, 5, 7]),) </code></pre>
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) &gt;&gt;&gt; 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 some cases the user may keep the browser open long after he's finished. </p> <p>Another approach would be to time user sessions or delete the temp files during routine maintenance.</p> <p>How do you go about it?</p>
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 some cases the user may keep the browser open long after he's finished. </p> <p>Another approach would be to time user sessions or delete the temp files during routine maintenance.</p> <p>How do you go about it?</p>
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 time (likely shorter than your automatic timeout length because if it was the same length it should already be taken care of)</p>
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 some cases the user may keep the browser open long after he's finished. </p> <p>Another approach would be to time user sessions or delete the temp files during routine maintenance.</p> <p>How do you go about it?</p>
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) - the variable b.</p>
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) - the variable b.</p>
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) - the variable b.</p>
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) &lt; 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) - the variable b.</p>
6
2009-01-11T02:21:43Z
432,247
<p>Is the following what you want?</p> <pre><code>if len(a) &lt; 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) &lt; len(b) else b </code></pre> <p>PS. Remember that Python does not use braces for its blocks, and that its ternary operator is different from C-like languages.</p>
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) - the variable b.</p>
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>&gt;&gt;&gt; print(min(a, b)) [1, 2, 3, 4, 5, 6, 7, 8] </code></pre> <p>To get the shortest length as an number, you can either <code>min</code> the <code>len()</code> of each list, or do <code>len(min())</code> (both are identical, choose which ever you find most readable)..</p> <pre><code>&gt;&gt;&gt; print(min( len(a), len(b) )) # or.. &gt;&gt;&gt; print(len( min(a, b) )) 8 </code></pre> <p>To print the lowest value in either list, you can supply the list as a single argument to <code>min()</code></p> <pre><code>&gt;&gt;&gt; a.extend(b) # Appends b to a &gt;&gt;&gt; print a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8] &gt;&gt;&gt; print(min(a)) 1 </code></pre> <p>Finally, another possibility, the list that has the lowest values in total:</p> <pre><code>&gt;&gt;&gt; max( sum(a), sum(b) ) 55 </code></pre> <p>To print the actual list with the highest <code>sum()</code>, you could either use the ternary operator, like..</p> <pre><code>&gt;&gt;&gt; print a if sum(a) &gt; sum(b) else b [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>..although I never really liked (or use) it, instead using the slight longer, regular if/else statements..</p> <pre><code>&gt;&gt;&gt; if sum(a) &gt; sum(b): ... print a ... else: ... print b ... [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre>
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) - the variable b.</p>
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) - the variable b.</p>
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 a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) </code></pre> <p>The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? </p> <p>Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax.</p> <pre><code>import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' </code></pre> <p>Thanks again!</p>
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 a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) </code></pre> <p>The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? </p> <p>Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax.</p> <pre><code>import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' </code></pre> <p>Thanks again!</p>
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 a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) </code></pre> <p>The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? </p> <p>Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax.</p> <pre><code>import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' </code></pre> <p>Thanks again!</p>
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&amp;rls=en-us&amp;q=windows+ssh&amp;ie=UTF-8&amp;oe=UTF-8" rel="nofollow">plenty more</a>.</p>
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 a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) </code></pre> <p>The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? </p> <p>Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax.</p> <pre><code>import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' </code></pre> <p>Thanks again!</p>
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 your use case perfectly none the less. To show you how simple Fabric is: the fab file and command for your script would look like this (not tested, but 99% sure it will work):</p> <p>fab_putfile.py:</p> <pre><code>from fabric.api import * env.hosts = ['THEHOST.com'] env.user = 'THEUSER' env.password = 'THEPASSWORD' def put_file(file): put(file, './THETARGETDIRECTORY/') # it's copied into the target directory </code></pre> <p>Then run the file with the fab command:</p> <pre><code>fab -f fab_putfile.py put_file:file=./path/to/my/file </code></pre> <p>And you're done! :)</p>
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 a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) </code></pre> <p>The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? </p> <p>Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax.</p> <pre><code>import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' </code></pre> <p>Thanks again!</p>
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.argv[1] host = "THEHOST.com" #hard-coded password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded with pysftp.Connection(host, username=username, password=password) as sftp: sftp.put(localpath, path) print 'Upload done.' </code></pre>
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 a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) </code></pre> <p>The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? </p> <p>Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax.</p> <pre><code>import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' </code></pre> <p>Thanks again!</p>
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/public_files/media/uploads') # change directory on remote server srv.put(file_path) # To download a file, replace put with get srv.close() # Close connection </code></pre> <p>pysftp is an easy to use sftp module that utilizes paramiko and pycrypto. It provides a simple interface to sftp.. Other things that you can do with pysftp which are quite useful:</p> <pre><code>data = srv.listdir() # Get the directory and file listing in a list srv.get(file_path) # Download a file from remote server srv.execute('pwd') # Execute a command on the server </code></pre> <p>More commands and about PySFTP <a href="http://pysftp.readthedocs.org/en/release_0.2.8/cookbook.html" rel="nofollow">here</a>.</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.com/thinkpython/thinkCSpy/">http://www.greenteapress.com/thinkpython/thinkCSpy/</a></p>
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/">at</a>. I know at least one guy will be using Haskell, so you will not be alone in pursuing an alternative route.</p>
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.com/ajmi/SICP_Examples">SICP_Examples</a> </p>
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 complexity of large programs. These concepts are illustrated primarily using the Python 3 programming language.<br> ...<br> Composing Programs is authored and maintained by John DeNero. The text was originally published as lecture notes for CS 61A at UC Berkeley and is based upon the Structure and Interpretation of Computer Programs by Harold Abelson and Gerald Jay Sussman.</p> </blockquote>
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 # -&gt; 5 test.__dict__['value'] # -&gt; 5 # BUT: attr_name = 'next_value' test.__dict__[attr_name] = 10 # -&gt; 'dictproxy' object does not support item assignment </code></pre>
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>&gt;&gt;&gt; class a(object): pass &gt;&gt;&gt; a.__dict__['wut'] = 4 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'dictproxy' object does not support item assignment &gt;&gt;&gt; setattr(a, 'wut', 7) &gt;&gt;&gt; a.wut 7 </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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>The xor operator on two booleans is logical xor (unlike on ints, where it's bitwise). Which makes sense, since <a href="http://docs.python.org/library/functions.html?highlight=bool#bool"><code>bool</code> is just a subclass of <code>int</code></a>, but is implemented to only have the values <code>0</code> and <code>1</code>. And logical xor is equivalent to bitwise xor when the domain is restricted to <code>0</code> and <code>1</code>.</p> <p>So the <code>logical_xor</code> function would be implemented like:</p> <pre><code>def logical_xor(str1, str2): return bool(str1) ^ bool(str2) </code></pre> <p>Credit to <a href="http://mail.python.org/pipermail/python-3000/2007-December/011560.html">Nick Coghlan on the Python-3000 mailing list</a>.</p>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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 <code>B</code></li> </ul> <p>To keep most of that way of thinking, my logical xor definintion would be:</p> <pre><code>def logical_xor(a, b): if bool(a) == bool(b): return False else: return a or b </code></pre> <p>That way it can return <code>a</code>, <code>b</code>, or <code>False</code>:</p> <pre><code>&gt;&gt;&gt; logical_xor('this', 'that') False &gt;&gt;&gt; logical_xor('', '') False &gt;&gt;&gt; logical_xor('this', '') 'this' &gt;&gt;&gt; logical_xor('', 'that') 'that' </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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></pre> <p>This dialect is inspired from a logical diagramming language I learned in school where "OR" was denoted by a box containing <code>≥1</code> (greater than or equal to 1) and "XOR" was denoted by a box containing <code>=1</code>.</p> <p>This has the advantage of correctly implementing exclusive or on multiple operands.</p> <ul> <li>"1 = a ^ b ^ c..." means the number of true operands is odd. This operator is "parity".</li> <li>"1 = a + b + c..." means exactly one operand is true. This is "exclusive or", meaning "one to the exclusion of the others".</li> </ul>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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 else b) if b else a </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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 that returns one of the operands, if possible, is much trickier, because no consensus exists as to which operand should be the chosen one, especially when there are more than two operands. For instance, should <code>xor(None, -1, [], True)</code> return <code>None</code>, <code>[]</code> or <code>False</code>? I bet each answer appears to some people as the most intuitive one.</p> <p>For either the True- or the False-result, there are as many as five possible choices: return first operand (if it matches end result in value, else boolean), return first match (if at least one exists, else boolean), return last operand (if ... else ...), return last match (if ... else ...), or always return boolean. Altogether, that's 5 ** 2 = 25 flavors of <code>xor</code>.</p> <pre><code>def xor(*operands, falsechoice = -2, truechoice = -2): """A single-evaluation, multi-operand, full-choice xor implementation falsechoice, truechoice: 0 = always bool, +/-1 = first/last operand, +/-2 = first/last match""" if not operands: raise TypeError('at least one operand expected') choices = [falsechoice, truechoice] matches = {} result = False first = True value = choice = None # avoid using index or slice since operands may be an infinite iterator for operand in operands: # evaluate each operand once only so as to avoid unintended side effects value = bool(operand) # the actual xor operation result ^= value # choice for the current operand, which may or may not match end result choice = choices[value] # if choice is last match; # or last operand and the current operand, in case it is last, matches result; # or first operand and the current operand is indeed first; # or first match and there hasn't been a match so far if choice &lt; -1 or (choice == -1 and value == result) or (choice == 1 and first) or (choice &gt; 1 and value not in matches): # store the current operand matches[value] = operand # next operand will no longer be first first = False # if choice for result is last operand, but they mismatch if (choices[result] == -1) and (result != value): return result else: # return the stored matching operand, if existing, else result as bool return matches.get(result, result) testcases = [ (-1, None, True, {None: None}, [], 'a'), (None, -1, {None: None}, 'a', []), (None, -1, True, {None: None}, 'a', []), (-1, None, {None: None}, [], 'a')] choices = {-2: 'last match', -1: 'last operand', 0: 'always bool', 1: 'first operand', 2: 'first match'} for c in testcases: print(c) for f in sorted(choices.keys()): for t in sorted(choices.keys()): x = xor(*c, falsechoice = f, truechoice = t) print('f: %d (%s)\tt: %d (%s)\tx: %s' % (f, choices[f], t, choices[t], x)) print() </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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 ^ bool(v) return sum </code></pre> <p>And usage is straightforward as well:</p> <pre><code>if xor(False, False, True, False): print "Hello World!" </code></pre> <p>As this is the generalized n-ary logical XOR, it's truth value will be True whenever the number of True operands is odd (and not only when exactly one is True, this is just one case in which n-ary XOR is True).</p> <p>Thus if you are in search of a n-ary predicate that is only True when exactly one of it's operands is, you might want to use:</p> <pre><code>def isOne(*vars): sum = bool(False) for v in vars: if sum and v: return False else: sum = sum or v return sum </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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 minimum, will check at least one of the elements twice. So it may increase code comprehension, but it doesn't lend to speed (which may differ negligibly depending on your use case). </p> <p>The second problem with this setup is that it checks for exclusivity regardless of the number of variables. This is may at first be regarded as a feature, but the first problem becomes a lot more significant as the number of variables increases (if they ever do).</p>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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 b) 10000000 loops, best of 3: 131 ns per loop </code></pre>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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>&gt;&gt;&gt; True is not True False &gt;&gt;&gt; True is not False True &gt;&gt;&gt; False is not True True &gt;&gt;&gt; False is not False False &gt;&gt;&gt; </code></pre> <p>And for your example string:</p> <pre><code>&gt;&gt;&gt; "abc" is not "" True &gt;&gt;&gt; 'abc' is not 'abc' False &gt;&gt;&gt; 'abc' is not '' True &gt;&gt;&gt; '' is not 'abc' True &gt;&gt;&gt; '' is not '' False &gt;&gt;&gt; </code></pre> <p>However; as they indicated above, it depends of the actual behavior you want to pull out about any couple strings, because strings aren't boleans... and even more: if you «Dive Into Python» you will find «The Peculiar Nature of "and" and "or"» <a href="http://www.diveintopython.net/power_of_introspection/and_or.html" rel="nofollow">http://www.diveintopython.net/power_of_introspection/and_or.html</a></p> <p>Sorry my writed English, it's not my born language.</p> <p>Regards.</p>
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("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
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>if x=True=1 and y=True=1 then the result would be |1-1|=0=False</li> <li>if x=False=0 and y=True=1 then the result would be |0-1|=1=True</li> </ol>
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,self).formfield_for_dbfield(db_field,**kwargs) </code></pre> <p>I can't work out how to adapt this to work for inlines.</p>
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,self).formfield_for_dbfield(db_field,**kwargs) </code></pre> <p>I can't work out how to adapt this to work for inlines.</p>
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 formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'name': kwargs['widget'] = MyWidget() return super(PictureInline,self).formfield_for_dbfield(db_field,**kwargs) </code></pre>
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,self).formfield_for_dbfield(db_field,**kwargs) </code></pre> <p>I can't work out how to adapt this to work for inlines.</p>
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> <pre><code>select * from car where mileage &lt; mileage_limit; </code></pre> <p>Using Q object in Django, I know I can compare columns with any value/object, e.g. if I wanted to get cars that have mileage say less than 100,000 it would be something like:</p> <pre><code>cars = Car.objects.filter(Q(mileage__lt=100000)) </code></pre> <p>Instead of a fixed value I would like to use the column name (in my case it is mileage_limit). So I would like to be able to do something like:</p> <pre><code>cars = Car.objects.filter(Q(mileage__lt=mileage_limit)) </code></pre> <p>However this results in an error, since it is expecting a value/object, not a column name. Is there a way to compare two columns using Q object? I feel like it would be a very commonly used feature and there should be an easy way to do this, however couldn't find anything about it in the documentation.</p> <p><em>Note: this is a simplified example, for which the use of Q object might seam to be unnecessary. However the real model has many more columns, and the real query is more complex, that's why I am using Q. Here in this question I just wanted to figure out specifically how to compare columns using Q.</em></p> <p><b>EDIT</b></p> <p>Apparently after release of Django 1.1 it would be possible to do the following:</p> <pre><code>cars = Car.objects.filter(mileage__lt=F('mileage_limit')) </code></pre> <p>Still not sure if F is supposed to work together with Q like this:</p> <pre><code>cars = Car.objects.filter(Q(mileage__lt=F('mileage_limit'))) </code></pre>
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:</p> <p><a href="http://www.srcco.de/v/pycocuma" rel="nofollow">http://www.srcco.de/v/pycocuma</a></p> <p><a href="http://pycocuma.sourcearchive.com/documentation/0.4.5-6-5/vcard_8py-source.html" rel="nofollow">http://pycocuma.sourcearchive.com/documentation/0.4.5-6-5/vcard_8py-source.html</a></p>
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>&gt;&gt;&gt; my_regex = r'(?P&lt;zip&gt;Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' &gt;&gt;&gt; addrs = "Zip: 10010 State: NY" &gt;&gt;&gt; y = re.search(my_regex, addrs) &gt;&gt;&gt; y.groupdict('zip') {'zip': 'Zip: 10010'} &gt;&gt;&gt; y.group(2) 'State: NY' </code></pre>
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 list of groups that are matched. "State: NY" is your third group. The first is the entire string and the second is "Zip: 10010".</p> <p>This was a relatively simple question by the way. I simply looked up the method documentation on google and found <a href="http://pydoc.org/1.6/pre.html" rel="nofollow">this page</a>. Google is your friend.</p>
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>&gt;&gt;&gt; my_regex = r'(?P&lt;zip&gt;Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' &gt;&gt;&gt; addrs = "Zip: 10010 State: NY" &gt;&gt;&gt; y = re.search(my_regex, addrs) &gt;&gt;&gt; y.groupdict('zip') {'zip': 'Zip: 10010'} &gt;&gt;&gt; y.group(2) 'State: NY' </code></pre>
6
2009-01-11T18:36:21Z
433,418
<p>regex definition:</p> <pre><code>(?P&lt;zip&gt;...) </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_]</p> <pre><code>y.groupdict('zip') </code></pre> <p>The groupdict method returns a dictionary with named groups as keys and their matches as values. In this case, the match for the "zip" group gets returned</p> <pre><code>y.group(2) </code></pre> <p>Return the match for the second group, which is a unnamed group "(...)"</p> <p>Hope that helps.</p>
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>&gt;&gt;&gt; my_regex = r'(?P&lt;zip&gt;Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' &gt;&gt;&gt; addrs = "Zip: 10010 State: NY" &gt;&gt;&gt; y = re.search(my_regex, addrs) &gt;&gt;&gt; y.groupdict('zip') {'zip': 'Zip: 10010'} &gt;&gt;&gt; y.group(2) 'State: NY' </code></pre>
6
2009-01-11T18:36:21Z
433,420
<p>The <code>(?P&lt;identifier&gt;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 using the match's <code>groupdict</code> method to get an <code>{identifier: match}</code> pair. Or you could use <code>y.group('zip')</code> if you're only interested in the match (which usually makes sense since you already know the identifier). You could also access the same match using its sequential number (1). The next match is unnamed, so the only way to access it is its number.</p>
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>&gt;&gt;&gt; my_regex = r'(?P&lt;zip&gt;Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' &gt;&gt;&gt; addrs = "Zip: 10010 State: NY" &gt;&gt;&gt; y = re.search(my_regex, addrs) &gt;&gt;&gt; y.groupdict('zip') {'zip': 'Zip: 10010'} &gt;&gt;&gt; y.group(2) 'State: NY' </code></pre>
6
2009-01-11T18:36:21Z
433,423
<pre><code># my_regex = r' &lt;= 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 is a digit, also works with [0-9] # \w is an alphanumeric character my_regex = r'(?P&lt;zip&gt;Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' addrs = "Zip: 10010 State: NY" # Runs the grep on the string y = re.search(my_regex, addrs) </code></pre>
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>&gt;&gt;&gt; my_regex = r'(?P&lt;zip&gt;Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' &gt;&gt;&gt; addrs = "Zip: 10010 State: NY" &gt;&gt;&gt; y = re.search(my_regex, addrs) &gt;&gt;&gt; y.groupdict('zip') {'zip': 'Zip: 10010'} &gt;&gt;&gt; y.group(2) 'State: NY' </code></pre>
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>&gt;&gt;&gt; my_regex = r'(?P&lt;zip&gt;Zip:\s*\d\d\d\d\d)\s*(?P&lt;state&gt;State:\s*\w\w)' &gt;&gt;&gt; addrs = "Zip: 10010 State: NY" &gt;&gt;&gt; y = re.search(my_regex, addrs) &gt;&gt;&gt; print y.groupdict() {'state': 'State: NY', 'zip': 'Zip: 10010'} </code></pre>
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>&gt;&gt;&gt; my_regex = r'(?P&lt;zip&gt;Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' &gt;&gt;&gt; addrs = "Zip: 10010 State: NY" &gt;&gt;&gt; y = re.search(my_regex, addrs) &gt;&gt;&gt; y.groupdict('zip') {'zip': 'Zip: 10010'} &gt;&gt;&gt; y.group(2) 'State: NY' </code></pre>
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 really follows its "readability counts" philosophy. For example, </p> <pre><code>class A: a = 10 b = "Madhu" def somemethod(self, arg1): self.c = 20.22 d = "some local variable" # do something .... ... def somemethod2 (self, arg2): self.c = "Changed the variable" # do something 2 ... </code></pre> <p>It's difficult to track the flow of code in situations where the instance variables are created upon use (i.e. <code>self.c</code> in the above snippet). It's not possible to see which instance variables are defined when reading a substantial amount of code written in this manner. It becomes very frustrating even when reading a class with just 6-8 methods and not more than 100-150 lines of code.</p> <p>I am interested in knowing if my reading of this code is skewed by C++/Java style, since most other languages follow the same approach as them. Is there a Pythonic way of reading this code more fluently? What made Python developers adopt this strategy keeping "readability counts" in mind?</p>
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 really follows its "readability counts" philosophy. For example, </p> <pre><code>class A: a = 10 b = "Madhu" def somemethod(self, arg1): self.c = 20.22 d = "some local variable" # do something .... ... def somemethod2 (self, arg2): self.c = "Changed the variable" # do something 2 ... </code></pre> <p>It's difficult to track the flow of code in situations where the instance variables are created upon use (i.e. <code>self.c</code> in the above snippet). It's not possible to see which instance variables are defined when reading a substantial amount of code written in this manner. It becomes very frustrating even when reading a class with just 6-8 methods and not more than 100-150 lines of code.</p> <p>I am interested in knowing if my reading of this code is skewed by C++/Java style, since most other languages follow the same approach as them. Is there a Pythonic way of reading this code more fluently? What made Python developers adopt this strategy keeping "readability counts" in mind?</p>
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 really follows its "readability counts" philosophy. For example, </p> <pre><code>class A: a = 10 b = "Madhu" def somemethod(self, arg1): self.c = 20.22 d = "some local variable" # do something .... ... def somemethod2 (self, arg2): self.c = "Changed the variable" # do something 2 ... </code></pre> <p>It's difficult to track the flow of code in situations where the instance variables are created upon use (i.e. <code>self.c</code> in the above snippet). It's not possible to see which instance variables are defined when reading a substantial amount of code written in this manner. It becomes very frustrating even when reading a class with just 6-8 methods and not more than 100-150 lines of code.</p> <p>I am interested in knowing if my reading of this code is skewed by C++/Java style, since most other languages follow the same approach as them. Is there a Pythonic way of reading this code more fluently? What made Python developers adopt this strategy keeping "readability counts" in mind?</p>
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 really follows its "readability counts" philosophy. For example, </p> <pre><code>class A: a = 10 b = "Madhu" def somemethod(self, arg1): self.c = 20.22 d = "some local variable" # do something .... ... def somemethod2 (self, arg2): self.c = "Changed the variable" # do something 2 ... </code></pre> <p>It's difficult to track the flow of code in situations where the instance variables are created upon use (i.e. <code>self.c</code> in the above snippet). It's not possible to see which instance variables are defined when reading a substantial amount of code written in this manner. It becomes very frustrating even when reading a class with just 6-8 methods and not more than 100-150 lines of code.</p> <p>I am interested in knowing if my reading of this code is skewed by C++/Java style, since most other languages follow the same approach as them. Is there a Pythonic way of reading this code more fluently? What made Python developers adopt this strategy keeping "readability counts" in mind?</p>
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're used in <em>every</em> language that i use - for me, not having to maintain a huge mental dictionary makes re-familiarizing myself with a bit of code much, much easier.</p>
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 really follows its "readability counts" philosophy. For example, </p> <pre><code>class A: a = 10 b = "Madhu" def somemethod(self, arg1): self.c = 20.22 d = "some local variable" # do something .... ... def somemethod2 (self, arg2): self.c = "Changed the variable" # do something 2 ... </code></pre> <p>It's difficult to track the flow of code in situations where the instance variables are created upon use (i.e. <code>self.c</code> in the above snippet). It's not possible to see which instance variables are defined when reading a substantial amount of code written in this manner. It becomes very frustrating even when reading a class with just 6-8 methods and not more than 100-150 lines of code.</p> <p>I am interested in knowing if my reading of this code is skewed by C++/Java style, since most other languages follow the same approach as them. Is there a Pythonic way of reading this code more fluently? What made Python developers adopt this strategy keeping "readability counts" in mind?</p>
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></li> <li><p>you normally don't bring instance variables into life in an arbitrary method. Instead, you typically have a constructor (__init__) that initializes all variables.</p></li> <li><p>you typically don't have instance variables named a, b, c. Instead, they have some speaking names.</p></li> </ul> <p>With these fixed, your example would be much more readable.</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 really follows its "readability counts" philosophy. For example, </p> <pre><code>class A: a = 10 b = "Madhu" def somemethod(self, arg1): self.c = 20.22 d = "some local variable" # do something .... ... def somemethod2 (self, arg2): self.c = "Changed the variable" # do something 2 ... </code></pre> <p>It's difficult to track the flow of code in situations where the instance variables are created upon use (i.e. <code>self.c</code> in the above snippet). It's not possible to see which instance variables are defined when reading a substantial amount of code written in this manner. It becomes very frustrating even when reading a class with just 6-8 methods and not more than 100-150 lines of code.</p> <p>I am interested in knowing if my reading of this code is skewed by C++/Java style, since most other languages follow the same approach as them. Is there a Pythonic way of reading this code more fluently? What made Python developers adopt this strategy keeping "readability counts" in mind?</p>
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 of possible things that can help.</p> <ul> <li>Using something like <a href="http://epydoc.sourceforge.net/" rel="nofollow">Epydoc</a>, you can specify all the instance variables a class will have. Be scrupulous about documenting your code, and be equally scrupulous about ensuring that your code and your documentation remain in sync.</li> <li>Adopt coding conventions that encourage the kind of code you find easiest to maintain. There's nothing better than setting a good example.</li> <li>Keep your classes and functions small and well-defined. If they get too big, break them up. It's easier to figure out what's going on that way.</li> <li>If you <strong>really</strong> want to insist that instance variables be declared before referenced, there are some metaclass tricks you can use. e.g., You can create a common base class that, using metaclass logic, enforces the convention that only variables that are declared when the subclass is declared can later be set.</li> </ul>
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 really follows its "readability counts" philosophy. For example, </p> <pre><code>class A: a = 10 b = "Madhu" def somemethod(self, arg1): self.c = 20.22 d = "some local variable" # do something .... ... def somemethod2 (self, arg2): self.c = "Changed the variable" # do something 2 ... </code></pre> <p>It's difficult to track the flow of code in situations where the instance variables are created upon use (i.e. <code>self.c</code> in the above snippet). It's not possible to see which instance variables are defined when reading a substantial amount of code written in this manner. It becomes very frustrating even when reading a class with just 6-8 methods and not more than 100-150 lines of code.</p> <p>I am interested in knowing if my reading of this code is skewed by C++/Java style, since most other languages follow the same approach as them. Is there a Pythonic way of reading this code more fluently? What made Python developers adopt this strategy keeping "readability counts" in mind?</p>
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 really follows its "readability counts" philosophy. For example, </p> <pre><code>class A: a = 10 b = "Madhu" def somemethod(self, arg1): self.c = 20.22 d = "some local variable" # do something .... ... def somemethod2 (self, arg2): self.c = "Changed the variable" # do something 2 ... </code></pre> <p>It's difficult to track the flow of code in situations where the instance variables are created upon use (i.e. <code>self.c</code> in the above snippet). It's not possible to see which instance variables are defined when reading a substantial amount of code written in this manner. It becomes very frustrating even when reading a class with just 6-8 methods and not more than 100-150 lines of code.</p> <p>I am interested in knowing if my reading of this code is skewed by C++/Java style, since most other languages follow the same approach as them. Is there a Pythonic way of reading this code more fluently? What made Python developers adopt this strategy keeping "readability counts" in mind?</p>
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 - if you at some point change your mind on the type of a variable, fixing type declarations can take more time than the fixes to actual code, in some cases, including the renaming of a type, but also cases where you use a different type with some similar methods and no superclass/subclass relationship.</p>
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 field (a date field) shows when this user visited a page on my site. </p> <p>I need to analyse this data so that i get the following results</p> <p>25 users visted on 1 day<br /> 100 users visted on 2 days<br /> 300 users visted on 4 days<br /> ... upto 25 days</p> <p>I am using python and don't know where to start ! </p> <p><strong>EDIT</strong></p> <p>I'm sorry it seems I wasnt clear enough about what I needed as a few people have given answers that are not what I'm looking for. </p> <p>I need to find out how many users visited on all the days e.g.<br /> 10 users visited on 25 days (or every day)</p> <p>Then I'd like the to list the same for each frequency of days from 1 - 25. So as per my original example above<br /> 25 users visited for only one day (out of the 25)<br /> 100 users visited on 2 days (out of the 25)<br /> etc </p> <p>I DONT need to know how many visited on each day<br /> thanks</p>
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 of dates on which they visited. </p> <pre><code>counts = defaultdict(int) for user in visits: v= len(visits[user]) count[v] += 1 </code></pre> <p>This gives you a dictionary of # visits, # of users with that many visits.</p> <p>Is that the kind of thing you're looking for?</p>
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 field (a date field) shows when this user visited a page on my site. </p> <p>I need to analyse this data so that i get the following results</p> <p>25 users visted on 1 day<br /> 100 users visted on 2 days<br /> 300 users visted on 4 days<br /> ... upto 25 days</p> <p>I am using python and don't know where to start ! </p> <p><strong>EDIT</strong></p> <p>I'm sorry it seems I wasnt clear enough about what I needed as a few people have given answers that are not what I'm looking for. </p> <p>I need to find out how many users visited on all the days e.g.<br /> 10 users visited on 25 days (or every day)</p> <p>Then I'd like the to list the same for each frequency of days from 1 - 25. So as per my original example above<br /> 25 users visited for only one day (out of the 25)<br /> 100 users visited on 2 days (out of the 25)<br /> etc </p> <p>I DONT need to know how many visited on each day<br /> thanks</p>
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 something like this to get the number for each day:</p> <pre><code>result = {} for (id, date) in data: if date not in result: result[date] = 1 else: result[date] += 1 </code></pre> <p>Now you can get the number of users for a specific date by doing something like this:</p> <pre><code>print result[some_date] </code></pre>
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 field (a date field) shows when this user visited a page on my site. </p> <p>I need to analyse this data so that i get the following results</p> <p>25 users visted on 1 day<br /> 100 users visted on 2 days<br /> 300 users visted on 4 days<br /> ... upto 25 days</p> <p>I am using python and don't know where to start ! </p> <p><strong>EDIT</strong></p> <p>I'm sorry it seems I wasnt clear enough about what I needed as a few people have given answers that are not what I'm looking for. </p> <p>I need to find out how many users visited on all the days e.g.<br /> 10 users visited on 25 days (or every day)</p> <p>Then I'd like the to list the same for each frequency of days from 1 - 25. So as per my original example above<br /> 25 users visited for only one day (out of the 25)<br /> 100 users visited on 2 days (out of the 25)<br /> etc </p> <p>I DONT need to know how many visited on each day<br /> thanks</p>
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): print('%d user(s) visited on %s' % (len(d[day]), day)) </code></pre> <p>It prints:</p> <pre><code>2 user(s) visited on 2008-12-01 1 user(s) visited on 2008-12-25 </code></pre>
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 field (a date field) shows when this user visited a page on my site. </p> <p>I need to analyse this data so that i get the following results</p> <p>25 users visted on 1 day<br /> 100 users visted on 2 days<br /> 300 users visted on 4 days<br /> ... upto 25 days</p> <p>I am using python and don't know where to start ! </p> <p><strong>EDIT</strong></p> <p>I'm sorry it seems I wasnt clear enough about what I needed as a few people have given answers that are not what I'm looking for. </p> <p>I need to find out how many users visited on all the days e.g.<br /> 10 users visited on 25 days (or every day)</p> <p>Then I'd like the to list the same for each frequency of days from 1 - 25. So as per my original example above<br /> 25 users visited for only one day (out of the 25)<br /> 100 users visited on 2 days (out of the 25)<br /> etc </p> <p>I DONT need to know how many visited on each day<br /> thanks</p>
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 [41]: l.sort() In [42]: l Out[42]: [[1, '2008-12-01'], [1, '2008-12-01'], [1, '2008-12-01'], [2, '2008-12-01'], [3, '3008-12-04']] In [43]: for key, group in groupby(l, lambda x: x[0]): ....: group=list(group) ....: print key,' :: ', len(group), ' :: ', group ....: ....: 1 :: 3 :: [[1, '2008-12-01'], [1, '2008-12-01'], [1, '2008-12-01']] 2 :: 1 :: [[2, '2008-12-01']] 3 :: 1 :: [[3, '3008-12-04']] </code></pre> <p>user::number of visits :: visit dates</p> <p>Here the user -1 visits on 2008-12-01 3 times, if you are looking to count only distinct dates then</p> <pre><code>for key, group in groupby(l, lambda x: x[0]): group=list(group) print key,' :: ', len(set([(lambda y: y[1])(each) for each in group])), ' :: ', group ....: ....: 1 :: 1 :: [[1, '2008-12-01'], [1, '2008-12-01'], [1, '2008-12-01']] 2 :: 1 :: [[2, '2008-12-01']] 3 :: 1 :: [[3, '3008-12-04']] </code></pre>
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 field (a date field) shows when this user visited a page on my site. </p> <p>I need to analyse this data so that i get the following results</p> <p>25 users visted on 1 day<br /> 100 users visted on 2 days<br /> 300 users visted on 4 days<br /> ... upto 25 days</p> <p>I am using python and don't know where to start ! </p> <p><strong>EDIT</strong></p> <p>I'm sorry it seems I wasnt clear enough about what I needed as a few people have given answers that are not what I'm looking for. </p> <p>I need to find out how many users visited on all the days e.g.<br /> 10 users visited on 25 days (or every day)</p> <p>Then I'd like the to list the same for each frequency of days from 1 - 25. So as per my original example above<br /> 25 users visited for only one day (out of the 25)<br /> 100 users visited on 2 days (out of the 25)<br /> etc </p> <p>I DONT need to know how many visited on each day<br /> thanks</p>
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 2 | 2008-12-04 2 | 2008-12-05 3 | 2008-12-04 4 | 2008-12-04 5 | 2008-12-05 5 | 2008-12-05 SELECT countdates, COUNT(userid) AS nusers FROM ( SELECT userid, COUNT (DISTINCT date) AS countdates FROM someList GROUP BY userid ) AS visits GROUP BY countdates HAVING countdates &lt;= 25 ORDER BY countdates; countdates | nusers ------------+-------- 1 | 3 3 | 1 5 | 1 </code></pre>
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 field (a date field) shows when this user visited a page on my site. </p> <p>I need to analyse this data so that i get the following results</p> <p>25 users visted on 1 day<br /> 100 users visted on 2 days<br /> 300 users visted on 4 days<br /> ... upto 25 days</p> <p>I am using python and don't know where to start ! </p> <p><strong>EDIT</strong></p> <p>I'm sorry it seems I wasnt clear enough about what I needed as a few people have given answers that are not what I'm looking for. </p> <p>I need to find out how many users visited on all the days e.g.<br /> 10 users visited on 25 days (or every day)</p> <p>Then I'd like the to list the same for each frequency of days from 1 - 25. So as per my original example above<br /> 25 users visited for only one day (out of the 25)<br /> 100 users visited on 2 days (out of the 25)<br /> etc </p> <p>I DONT need to know how many visited on each day<br /> thanks</p>
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>&gt;&gt;&gt; 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, '2008-12-04']] &gt;&gt;&gt; all_dates = sorted(set([d for d in [x[1] for x in log]])) &gt;&gt;&gt; for i in range(0, len(all_dates)): ... log_slice = [d for d in log if d[1] &lt;= all_dates[i]] ... num_users = len(set([u for u in [x[0] for x in log_slice]])) ... print "%d users visited in %d days" % (num_users, i + 1) ... 2 users visited in 1 days 2 users visited in 2 days 4 users visited in 3 days &gt;&gt;&gt; </code></pre>
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></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))]) return newseq </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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 that's often a consequence of interfacing with the outside world.</p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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 chunks(ints,4): foo += x1 + x2 + x3 + x4 for chunk in chunks(ints,4): foo += sum(chunk) </code></pre> <p>Another way:</p> <pre><code>import itertools def chunks2(iterable,size,filler=None): it = itertools.chain(iterable,itertools.repeat(filler,size-1)) chunk = tuple(itertools.islice(it,size)) while len(chunk) == size: yield chunk chunk = tuple(itertools.islice(it,size)) # x2, x3 and x4 could get the value 0 if the length is not # a multiple of 4. for x1,x2,x3,x4 in chunks2(ints,4,0): foo += x1 + x2 + x3 + x4 </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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 &lt;= 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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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' 'xt' print '|'.join(chunker(text, 10)) # I am a ver|y, very he|lpful text animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish'] for group in chunker(animals, 3): print group # ['cat', 'dog', 'rabbit'] # ['duck', 'bird', 'cow'] # ['gnu', 'fish'] </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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(result) &gt; 0: yield tuple(result) for x in get_chunk([1,2,3,4,5,6,7,8,9,10], 3): print x (1, 2, 3) (4, 5, 6) (7, 8, 9) (10,) </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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 what the <code>zip()</code> function produces:</p> <pre><code>&gt;&gt;&gt; print l1 [0, 1, 2, 3] &gt;&gt;&gt; print l2 [4, 5, 6, 7] &gt;&gt;&gt; print l3 [8, 9, 10, 11] &gt;&gt;&gt; print l4 [12, 13, 14, 15] &gt;&gt;&gt; print zip(l1, l2, l3, l4) [(0, 4, 8, 12), (1, 5, 9, 13), (2, 6, 10, 14), (3, 7, 11, 15)] </code></pre> <p>If the lists are large, and you don't want to combine them into a bigger list, use <code>itertools.izip()</code>, which produces an iterator, rather than a list.</p> <pre><code>from itertools import izip for i1, i2, i3, i4 in izip(l1, l2, l3, l4): ... </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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 return izip_longest(*args, fillvalue=fillvalue) </code></pre> <p><strong>Example</strong><br> In pseudocode to keep the example terse.</p> <pre><code>grouper('ABCDEFG', 3, 'x') --&gt; 'ABC' 'DEF' 'Gxx' </code></pre> <p><strong>Note:</strong> <code>izip_longest</code> is new to Python 2.6. In Python 3 use <code>zip_longest</code>.</p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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>&gt;&gt;&gt; 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 if it isn't.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; s = '1234567890' &gt;&gt;&gt; chunker(s, 3) [('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9')] &gt;&gt;&gt; chunker(s, 4) [('1', '2', '3', '4'), ('5', '6', '7', '8')] &gt;&gt;&gt; chunker(s, 5) [('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0')] </code></pre> <p>Or using <a href="http://docs.python.org/library/itertools.html" rel="nofollow">itertools.izip</a> to return an iterator instead of a list:</p> <pre><code>&gt;&gt;&gt; from itertools import izip &gt;&gt;&gt; def chunker(iterable, chunksize): ... return izip(*[iter(iterable)]*chunksize) </code></pre> <p>Padding can be fixed using <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python#312644">@ΤΖΩΤΖΙΟΥ's answer</a>:</p> <pre><code>&gt;&gt;&gt; from itertools import chain, izip, repeat &gt;&gt;&gt; def chunker(iterable, chunksize, fillvalue=None): ... it = chain(iterable, repeat(fillvalue, chunksize-1)) ... args = [it] * chunksize ... return izip(*args) </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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>&gt;&gt;&gt; def chunker(iterable, chunksize): ... return map(None,*[iter(iterable)]*chunksize) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; s = '1234567890' &gt;&gt;&gt; chunker(s, 3) [('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9'), ('0', None, None)] &gt;&gt;&gt; chunker(s, 4) [('1', '2', '3', '4'), ('5', '6', '7', '8'), ('9', '0', None, None)] &gt;&gt;&gt; chunker(s, 5) [('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0')] </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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') --&gt; ABC DEF Gxx" args = [iter(iterable)] * n return itertools.izip_longest(fillvalue=fillvalue, *args) </code></pre> <p>Using ipython's <code>%timeit</code> on my mac book air, I get 47.5 us per loop.</p> <p>However, this really doesn't work for me since the results are padded to be even sized groups. A solution without the padding is slightly more complicated. The most naive solution might be:</p> <pre><code>def grouper(size, iterable): i = iter(iterable) while True: out = [] try: for _ in range(size): out.append(i.next()) except StopIteration: yield out break yield out </code></pre> <p>Simple, but pretty slow: 693 us per loop</p> <p>The best solution I could come up with uses <code>islice</code> for the inner loop:</p> <pre><code>def grouper(size, iterable): it = iter(iterable) while True: group = tuple(itertools.islice(it, None, size)) if not group: break yield group </code></pre> <p>With the same dataset, I get 305 us per loop.</p> <p>Unable to get a pure solution any faster than that, I provide the following solution with an important caveat: If your input data has instances of <code>filldata</code> in it, you could get wrong answer.</p> <pre><code>def grouper(n, iterable, fillvalue=None): #"grouper(3, 'ABCDEFG', 'x') --&gt; ABC DEF Gxx" args = [iter(iterable)] * n for i in itertools.izip_longest(fillvalue=fillvalue, *args): if tuple(i)[-1] == fillvalue: yield tuple(v for v in i if v != fillvalue) else: yield i </code></pre> <p>I really don't like this answer, but it is significantly faster. 124 us per loop</p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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 memory<br> 5) No padding of fill values at the end of the list</p> <p>That being said, I haven't timed it so it might be slower than some of the more clever methods, and some of the advantages may be irrelevant given the use case.</p> <pre><code>def chunkiter(iterable, size): def inneriter(first, iterator, size): yield first for _ in xrange(size - 1): yield iterator.next() it = iter(iterable) while True: yield inneriter(it.next(), it, size) In [2]: i = chunkiter('abcdefgh', 3) In [3]: for ii in i: for c in ii: print c, print '' ...: a b c d e f g h </code></pre> <p><strong>Update:</strong><br> A couple of drawbacks due to the fact the inner and outer loops are pulling values from the same iterator:<br> 1) continue doesn't work as expected in the outer loop - it just continues on to the next item rather than skipping a chunk. However, this doesn't seem like a problem as there's nothing to test in the outer loop.<br> 2) break doesn't work as expected in the inner loop - control will wind up in the inner loop again with the next item in the iterator. To skip whole chunks, either wrap the inner iterator (ii above) in a tuple, e.g. <code>for c in tuple(ii)</code>, or set a flag and exhaust the iterator.<br></p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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 &gt;&gt;&gt; (1, 2, 3, 4) &gt;&gt;&gt; (5, 6, 7, 8) </code></pre> <p>This way you won't get the last partial chunk. If you want to get <code>(9, None, None, None)</code> as last chunk, just use <code>izip_longest</code> from <code>itertools</code>.</p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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 res = [] if res: yield res </code></pre> <p>List:</p> <pre><code>&gt;&gt;&gt; list(chunker([i for i in range(10)], 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] </code></pre> <p>Set:</p> <pre><code>&gt;&gt;&gt; list(chunker(set([i for i in range(10)]), 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] </code></pre> <p>Generator:</p> <pre><code>&gt;&gt;&gt; list(chunker((i for i in range(10)), 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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. &gt;&gt;&gt; group_by([1,2,3,4,5], 2) [[1, 2], [3, 4], [5]] """ sublist = [] for index, item in enumerate(iterable): if index &gt; 0 and index % size == 0: yield sublist sublist = [] sublist.append(item) if sublist: yield sublist </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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://stackoverflow.com/a/434314/577088">Markus Jarderot</a>’s answer):</p> <pre><code>from itertools import islice, chain, repeat def group_pad(it, size, pad=None): it = chain(iter(it), repeat(pad)) return iter(lambda: tuple(islice(it, size)), (pad,) * size) </code></pre> <p>These can even be combined for optional padding:</p> <pre><code>_no_pad = object() def group(it, size, pad=_no_pad): if pad == _no_pad: it = iter(it) sentinel = () else: it = chain(iter(it), repeat(pad)) sentinel = (pad,) * size return iter(lambda: tuple(islice(it, size)), sentinel) </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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 funcy import partition for a, b, c, d in partition(4, ints): foo += a * b * c * d </code></pre> <p>These functions also has iterator versions <code>ipartition</code> and <code>ichunks</code>, which will be more efficient in this case.</p> <p>You can also peek at <a href="https://github.com/Suor/funcy/blob/1.0.0/funcy/seqs.py#L316" rel="nofollow">their implementation</a>.</p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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>&gt;&gt;&gt; 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, 24, 25, 26, 27, 28, 29] 3 [30, 31, 32, 33, 34] &gt;&gt;&gt; </code></pre> <p>I checked <code>groupby</code> and it doesn't convert to list or use <code>len</code> so I (think) this will delay resolution of each value until it is actually used. Sadly none of the available answers (at this time) seemed to offer this variation.</p> <p>Obviously if you need to handle each item in turn nest a for loop over g:</p> <pre><code>for k,g in itertools.groupby(xrange(35), lambda x: x/10): for i in g: # do what you need to do with individual items # now do what you need to do with the whole group </code></pre> <p>My specific interest in this was the need to consume a generator to submit changes in batches of up to 1000 to the gmail API:</p> <pre><code> messages = a_generator_which_would_not_be_smart_as_a_list for idx, batch in groupby(messages, lambda x: x/1000): batch_request = BatchHttpRequest() for message in batch: batch_request.add(self.service.users().messages().modify(userId='me', id=message['id'], body=msg_labels)) http = httplib2.Http() self.credentials.authorize(http) batch_request.execute(http=http) </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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)) chunk = reductor(chunk_generator()) while condition(chunk): yield chunk chunk = reductor(chunk_generator()) </code></pre> <h1>Arguments:</h1> <h3>Obvious ones</h3> <ul> <li><code>iterable</code> is any iterable / iterator / generator containg / generating / iterating over input data,</li> <li><code>size</code> is, of course, size of chunk you want get,</li> </ul> <h3>More interesting</h3> <ul> <li><p><code>reductor</code> is a callable, which receives generator iterating over content of chunk.<br> I'd expect it to return sequence or string, but I don't demand that.</p> <p>You can pass as this argument for example <code>list</code>, <code>tuple</code>, <code>set</code>, <code>frozenset</code>,<br> or anything fancier. I'd pass this function, returning string<br> (provided that <code>iterable</code> contains / generates / iterates over strings):</p> <pre><code>def concatenate(iterable): return ''.join(iterable) </code></pre> <p><sup>Note that <code>reductor</code> can cause closing generator by raising exception.</sup></p></li> <li><p><code>condition</code> is a callable which receives anything what <code>reductor</code> returned.<br> It decides to approve &amp; yield it (by returning anything evaluating to <code>True</code>),<br> or to decline it &amp; finish generator's work (by returning anything other or raising exception).</p> <p>When number of elements in <code>iterable</code> is not divisible by <code>size</code>, when <code>it</code> gets exhausted, <code>reductor</code> will receive generator generating less elements than <code>size</code>.<br> Let's call these elements <em>lasts elements</em>.</p> <p>I invited two functions to pass as this argument: </p> <ul> <li><p><code>lambda x:x</code> - the <em>lasts elements</em> will be yielded.</p></li> <li><p><code>lambda x: len(x)==&lt;size&gt;</code> - the <em>lasts elements</em> will be rejected.<br> <sup>replace <code>&lt;size&gt;</code> using number equal to <code>size</code></sup></p></li> </ul></li> </ul>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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> Of course you can write <code>''.join(chunker(...))</code>, but the temporary tuple is constructed anyway.</p> <p>You can get rid of the temporary tuple by writing own <code>zip</code>, like this:</p> <pre><code>class IteratorExhausted(Exception): pass def translate_StopIteration(iterable, to=IteratorExhausted): for i in iterable: yield i raise to # StopIteration would get ignored because this is generator, # but custom exception can leave the generator. def custom_zip(*iterables, reductor=tuple): iterators = tuple(map(translate_StopIteration, iterables)) while True: try: yield reductor(next(i) for i in iterators) except IteratorExhausted: # when any of iterators get exhausted. break </code></pre> <p>Then</p> <pre><code>def chunker(data, size, reductor=tuple): return custom_zip(*[iter(data)]*size, reductor=reductor) </code></pre> <p>Example usage:</p> <pre><code>&gt;&gt;&gt; for i in chunker('12345', 2): ... print(repr(i)) ... ('1', '2') ('3', '4') &gt;&gt;&gt; for i in chunker('12345', 2, ''.join): ... print(repr(i)) ... '12' '34' </code></pre>
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): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
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:</p> <pre><code>&gt;&gt;&gt; def foo(): ... i = 0 ... while True: ... i += 1 ... yield i ... &gt;&gt;&gt; c = chunks(foo(), 3) &gt;&gt;&gt; c.next() (1, 2, 3) &gt;&gt;&gt; c.next() (4, 5, 6) &gt;&gt;&gt; list(chunks('abcdefg', 2)) [('a', 'b'), ('c', 'd'), ('e', 'f')] </code></pre>
1
2015-04-10T18:07:52Z
[ "python", "list", "loops", "optimization", "chunks" ]