title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How do I do conditional array arithmetic on a numpy array? | 3,409,255 | 8 | 2010-08-04T19:47:12Z | 3,409,378 | 7 | 2010-08-04T20:05:38Z | [
"python",
"numpy"
] | I'm trying to get a better grip on numpy arrays, so I have a sample question to ask about them:
Say I have a numpy array called a. I want to perform an operation on a that increments all the values inside it that are less than 0 and leaves the rest alone. for example, if I had:
```
a = np.array([1,2,3,-1,-2,-3])
```
... | To mutate it:
```
a[a<0] += 1
```
To leave the original array alone:
```
a+[a<0]
``` |
Define dtypes in NumPy using a list? | 3,410,147 | 3 | 2010-08-04T21:51:53Z | 3,410,940 | 12 | 2010-08-05T00:38:40Z | [
"python",
"numpy"
] | I just am having a problem with NumPy dtypes. Essentially I'm trying to create a table that looks like the following (and then save it using rec2csv):
```
name1 name2 name3 . . .
name1 # # #
name2 # # #
name2 # # #
.
.
.
```
The matrix (numerical array in the center), is... | The following code might help:
```
import numpy as np
dt = np.dtype([('name1', '|S10'), ('name2', '<f8')])
tuplelist=[
('n1', 1.2),
('n2', 3.4),
]
arr = np.array(tuplelist, dtype=dt)
print(arr['name1'])
# ['n1' 'n2']
print(arr['name2'])
# [ 1.2 3.4]
```
Your immediate problem was that `np.dtype` e... |
python: unhashable type error | 3,410,206 | 11 | 2010-08-04T22:03:13Z | 3,410,267 | 16 | 2010-08-04T22:12:23Z | [
"python"
] | ```
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
do_work()
File "C:\pythonwork\readthefile080410.py", line 14, in do_work
populate_frequency5(e,data)
File "C:\pythonwork\readthefile080410.py", line 157, in populate_frequency5
data=medications_minimum3(data,[drug.upper()]... | ```
counter[row[11]]+=1
```
You don't show what `data` is, but apparently when you loop through its rows, `row[11]` is turning out to be a `list`. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use `row[11]` as a key causes the `defaultdict` to complain that it is a mutable, i.... |
What is the difference between StringIO and io.StringIO in Python2.7? | 3,410,309 | 18 | 2010-08-04T22:18:46Z | 3,410,461 | 19 | 2010-08-04T22:44:02Z | [
"python",
"string"
] | Besides the obvious (one is a type, the other a class)? What should be preferred? Any notable difference in use cases, perhaps? | <http://docs.python.org/library/io.html#io.StringIO>
<http://docs.python.org/library/stringio.html>
I see this.
> An in-memory stream for unicode text. It inherits TextIOWrapper.
>
> This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).
`io.StringIO`... |
Does Django have BDD testing tools comparable to Rails' testing tools? | 3,410,447 | 14 | 2010-08-04T22:41:31Z | 3,428,166 | 16 | 2010-08-06T22:10:17Z | [
"python",
"ruby-on-rails",
"django",
"testing",
"bdd"
] | Ruby/Rails enjoy some really nice and powerful Behavior Driven Design/Development testing frameworks like [Cucumber](http://cukes.info/) and [RSpec](http://rspec.info/).
Does Python/Django enjoy the same thing (I'm not talking about simple unit testing like PyUnit)? | There is a new tools called [Lettuce](http://lettuce.it/ "Lettuce") that promises to be a Pythonic version of Cucumber. It is starting with Django integration. That plus the existing testing tools in Django make it pretty good for unit testing.
There's also a tool called [Windmill](http://www.getwindmill.com/) that pr... |
How do I use SQL parameters with python? | 3,410,455 | 4 | 2010-08-04T22:43:17Z | 3,410,820 | 13 | 2010-08-05T00:03:04Z | [
"python",
"pymssql"
] | I am using python 2.7 and [pymssql 1.9.908](http://code.google.com/p/pymssql/).
In .net to query the database I would do something like this:
```
using (SqlCommand com = new SqlCommand("select * from Customer where CustomerId = @CustomerId", connection))
{
com.Parameters.AddWithValue("@CustomerID", CustomerID);
... | After creating a connection object `db`:
```
cursor = db.execute('SELECT * FROM Customer WHERE CustomerID = %s', [customer_id])
```
then use any of the `fetch...` methods of the resulting `cursor` object.
Don't be fooled by the `%s` part: this is NOT string formatting, it's parameter substitution (different DB API m... |
Python's join() won't join the string representation (__str__) of my object | 3,410,647 | 2 | 2010-08-04T23:26:35Z | 3,410,655 | 9 | 2010-08-04T23:28:52Z | [
"python"
] | I'm not sure what I'm doing wrong here:
```
>>> class Stringy(object):
... def __str__(self):
... return "taco"
... def __repr__(self):
... return "taco"
...
>>> lunch = Stringy()
>>> lunch
taco
>>> str(lunch)
'taco'
>>> '-'.join(('carnitas',lunch))
Traceback (most recent call last):
... | no you have to convert it to str yourself
```
'-'.join(('carnitas',str(lunch)))
```
if you have to do it for a whole sequence of items
```
'-'.join(str(x) for x in seq)
```
or
```
'-'.join(map(str, seq))
```
for your particular case you can just write
```
'carnitas-'+str(lunch)
``` |
How to round a number to significant figures in Python | 3,410,976 | 75 | 2010-08-05T00:48:04Z | 3,411,435 | 82 | 2010-08-05T02:57:33Z | [
"python",
"math",
"rounding"
] | I need to round a float to be displayed in a UI. E.g, to one significant figure:
1234 -> 1000
0.12 -> 0.1
0.012 -> 0.01
0.062 -> 0.06
6253 -> 6000
1999 -> 2000
Is there a nice way to do this using the Python library, or do I have to write it myself? | You can use negative numbers to round integers:
```
>>> round(1234, -3)
1000.0
```
Thus if you need only most significant digit:
```
>>> from math import log10, floor
>>> def round_to_1(x):
... return round(x, -int(floor(log10(abs(x)))))
...
>>> round_to_1(0.0232)
0.02
>>> round_to_1(1234243)
1000000.0
>>> round_... |
How to round a number to significant figures in Python | 3,410,976 | 75 | 2010-08-05T00:48:04Z | 3,411,731 | 62 | 2010-08-05T04:24:19Z | [
"python",
"math",
"rounding"
] | I need to round a float to be displayed in a UI. E.g, to one significant figure:
1234 -> 1000
0.12 -> 0.1
0.012 -> 0.01
0.062 -> 0.06
6253 -> 6000
1999 -> 2000
Is there a nice way to do this using the Python library, or do I have to write it myself? | %g in string formatting will format a float rounded to some number of significant figures. It will sometimes use 'e' scientific notation, so convert the rounded string back to a float then through %s string formatting.
```
>>> '%s' % float('%.1g' % 1234)
'1000'
>>> '%s' % float('%.1g' % 0.12)
'0.1'
>>> '%s' % float('%... |
How to round a number to significant figures in Python | 3,410,976 | 75 | 2010-08-05T00:48:04Z | 3,413,529 | 20 | 2010-08-05T09:49:43Z | [
"python",
"math",
"rounding"
] | I need to round a float to be displayed in a UI. E.g, to one significant figure:
1234 -> 1000
0.12 -> 0.1
0.012 -> 0.01
0.062 -> 0.06
6253 -> 6000
1999 -> 2000
Is there a nice way to do this using the Python library, or do I have to write it myself? | If you want to have other than 1 significant decimal (otherwise the same as Evgeny):
```
>>> from math import log10, floor
>>> def round_sig(x, sig=2):
... return round(x, sig-int(floor(log10(x)))-1)
...
>>> round_sig(0.0232)
0.023
>>> round_sig(0.0232, 1)
0.02
>>> round_sig(1234243, 3)
1230000.0
``` |
Summarizing a dictionary of arrays in Python | 3,411,025 | 4 | 2010-08-05T00:58:56Z | 3,411,052 | 7 | 2010-08-05T01:04:44Z | [
"python",
"algorithm",
"arrays",
"dictionary"
] | I got the following dictionary:
```
mydict = {
'foo': [1,19,2,3,24,52,2,6], # sum: 109
'bar': [50,5,9,7,66,3,2,44], # sum: 186
'another': [1,2,3,4,5,6,7,8], # sum: 36
'entry': [0,0,0,2,99,4,33,55], # sum: 193
'onemore': [21,22,23,24,25,26,27,28] # sum: 196
}
```
I need to ... | It's easy to do with a sort:
```
sorted(mydict.iteritems(), key=lambda tup: sum(tup[1]), reverse=True)[:3]
```
This is reasonable if the ratio is similar to this one (3 / 5). If it's larger, you'll want to avoid the sort (O(n log n)), since top 3 can be done in O(n). For instance, using [heapq](http://docs.python.org... |
Why does the Python 2.7 AMD 64 installer seem to run Python in 32 bit mode? | 3,411,079 | 6 | 2010-08-05T01:13:54Z | 3,411,134 | 11 | 2010-08-05T01:30:54Z | [
"python",
"windows",
"64bit"
] | I've installed Python 2.7 from the python-2.7.amd64.msi package from python.org. It installs and runs correctly, but seems to be in 32-bit mode, despite the fact that the installer was a 64 bit installer.
```
Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "... | See the discussion [here](https://mail.python.org/pipermail/python-list/2008-December/511178.html). It's from 2.6.1, but it seems to still apply. I haven't seen evidence to the contrary anywhere, at least. The gist of the matter (quoted from that link) is:
> This is by design. In their infinitive wisdom Microsoft has ... |
Using module's own objects in __main__.py | 3,411,293 | 30 | 2010-08-05T02:15:58Z | 3,414,096 | 15 | 2010-08-05T11:11:18Z | [
"python",
"main",
"init"
] | Iâm trying to access a moduleâs data from inside its `__main__.py`.
The structure is as follows:
```
mymod/
__init__.py
__main__.py
```
Now, if I expose a variable in `__init__.py` like this:
```
__all__ = ['foo']
foo = {'bar': 'baz'}
```
How can I access `foo` from `__main__.py`? | You need to either have the package already in `sys.path`, add the directory containing `mymod` to `sys.path` in `__main__.py`, or use the `-m` switch.
To add `mymod` to the path would look something like this (in `__main__.py`):
```
import sys
import os
path = os.path.dirname(sys.modules[__name__].__file__)
path = o... |
Python - '>>' operator | 3,411,749 | 9 | 2010-08-05T04:29:21Z | 3,411,760 | 15 | 2010-08-05T04:32:40Z | [
"python",
"operators"
] | What does the >> operator do?
For example 10 >> 1 = 5
Thanks | It's the right bit shift operator, 'moves' all bits once to the right.
10 in binary is
1010
shifted to the right it turns to
0101
which is 5 |
Multiple character replace with python | 3,411,771 | 43 | 2010-08-05T04:34:16Z | 3,411,790 | 10 | 2010-08-05T04:39:07Z | [
"python",
"string",
"replace"
] | I need to replace some characters as follows : & -> \&, # -> \#, ...
I coded as follows, but I guess there should be some better way. Any hints?
```
strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
``` | Are you always going to prepend a backslash? If so, try
```
import re
rx = re.compile('([&#])')
# ^^ fill in the characters here.
strs = rx.sub('\\\\\\1', strs)
```
It may not be the most efficient method but I think it is the easiest. |
Multiple character replace with python | 3,411,771 | 43 | 2010-08-05T04:34:16Z | 3,412,090 | 30 | 2010-08-05T05:54:54Z | [
"python",
"string",
"replace"
] | I need to replace some characters as follows : & -> \&, # -> \#, ...
I coded as follows, but I guess there should be some better way. Any hints?
```
strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
``` | ```
>>> string="abc&def#ghi"
>>> for ch in ['&','#']:
... if ch in string:
... string=string.replace(ch,"\\"+ch)
...
>>> print string
abc\&def\#ghi
``` |
Multiple character replace with python | 3,411,771 | 43 | 2010-08-05T04:34:16Z | 27,086,669 | 96 | 2014-11-23T07:37:49Z | [
"python",
"string",
"replace"
] | I need to replace some characters as follows : & -> \&, # -> \#, ...
I coded as follows, but I guess there should be some better way. Any hints?
```
strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...
``` | # Replacing two characters
I timed all the methods in the current answers along with one extra.
With an input string of `abc&def#ghi` and replacing & -> \& and # -> #, the fastest was to chain together the replacements like: `text.replace('&', '\&').replace('#', '\#')`.
Timings for each function:
* a) 1000000 loops... |
Querying Many to many fields in django template | 3,411,961 | 6 | 2010-08-05T05:25:06Z | 3,411,979 | 23 | 2010-08-05T05:29:20Z | [
"python",
"django",
"django-models",
"django-templates",
"django-views"
] | This may not be relevant but just wanted to ask,
IF an object is passed from views to template and in the template will i be able to query many to many fields
Models code:
```
class Info(models.Model):
xls_answer = models.TextField(null=True,blank=True)
class Upload(models.Model):
access = models.In... | In general, you can follow anything that's an attribute or a method call with no arguments through pathing in the django template system.
For the view code above, something like
```
{% for objs in obj_arr %}
{% for answer in objs.answers.all %}
{{ answer.someattribute }}
{% endfor %}
{% endfor %}
```
should do wha... |
Python cut a string after Xth sentence | 3,412,316 | 3 | 2010-08-05T06:42:07Z | 3,412,484 | 14 | 2010-08-05T07:11:12Z | [
"python",
"string"
] | I have to cut a **unicode** string which is actually an article (contains sentences) I want to cut this article string after Xth sentence in python.
A good indicator of a sentence ending is that it ends with full stop (".") and the word after start with capital name. Such as
```
myarticle == "Hi, this is my first sen... | Consider downloading the Natural Language Toolkit ([`NLTK`](http://www.nltk.org/)). Then you can create sentences that will not break for things like "U.S.A." or fail to split sentences that end in "?!".
```
>>> import nltk
>>> paragraph = u"Hi, this is my first sentence. And this is my second. Yet this is my third."
... |
Python not sorting unicode properly. Strcoll doesn't help | 3,412,933 | 15 | 2010-08-05T08:25:52Z | 3,413,436 | 14 | 2010-08-05T09:37:04Z | [
"python",
"unicode",
"locale"
] | I've got a problem with sorting lists using unicode collation in Python 2.5.1 and 2.6.5 on OSX, as well as on Linux.
```
import locale
locale.setlocale(locale.LC_ALL, 'pl_PL.UTF-8')
print [i for i in sorted([u'a', u'z', u'Ä
'], cmp=locale.strcoll)]
```
Which should print:
```
[u'a', u'Ä
', u'z']
```
But instead ... | Apparently, the only way for sorting to work on all platforms is to use the ICU library with PyICU bindings ([PyICU on PyPI](https://pypi.python.org/pypi/PyICU/)).
On OS X: `sudo port install py26-pyicu`, minding bug described here: <https://svn.macports.org/ticket/23429> (oh the joy of using macports).
PyICUs docume... |
How to create an empty R vector to add new items | 3,413,879 | 72 | 2010-08-05T10:39:48Z | 3,414,062 | 42 | 2010-08-05T11:06:43Z | [
"python",
"vector",
"rpy2"
] | I want to use R in Python, as provided by the module Rpy2. I notice that R has very convenient `[]` operations by which you can extract the specific columns or lines. How could I achieve such a function by Python scripts?
My idea is to create an R vector and add those wanted elements into this vector so that the final... | I pre-allocate a vector with
```
> (a <- rep(NA, 10))
[1] NA NA NA NA NA NA NA NA NA NA
```
You can then use [] to insert values into it. |
How to create an empty R vector to add new items | 3,413,879 | 72 | 2010-08-05T10:39:48Z | 3,414,437 | 21 | 2010-08-05T12:00:21Z | [
"python",
"vector",
"rpy2"
] | I want to use R in Python, as provided by the module Rpy2. I notice that R has very convenient `[]` operations by which you can extract the specific columns or lines. How could I achieve such a function by Python scripts?
My idea is to create an R vector and add those wanted elements into this vector so that the final... | You can create an empty vector like so
```
vec <- numeric(0)
```
And then add elements using c()
```
vec <- c(vec, 1:5)
```
However as romunov says, it's much better to pre-allocate a vector and then populate it (as this avoids reallocating a new copy of your vector every time you add elements) |
How to create an empty R vector to add new items | 3,413,879 | 72 | 2010-08-05T10:39:48Z | 3,414,543 | 81 | 2010-08-05T12:14:26Z | [
"python",
"vector",
"rpy2"
] | I want to use R in Python, as provided by the module Rpy2. I notice that R has very convenient `[]` operations by which you can extract the specific columns or lines. How could I achieve such a function by Python scripts?
My idea is to create an R vector and add those wanted elements into this vector so that the final... | ```
vec <- vector()
```
See also vector help
```
?vector
``` |
TypeError uploading image file to Amazon S3 in Django using BOTO Library | 3,414,778 | 6 | 2010-08-05T12:47:55Z | 3,426,117 | 7 | 2010-08-06T17:18:33Z | [
"python",
"django",
"file-upload",
"amazon-s3",
"boto"
] | I am a total beginner to programming and Django so I'd appreciate help that beginner can get his head round!
I was following a tutorial to show how to upload images to an Amazon S3 account with the Boto library but I think it is for an older version of Django (I'm on 1.1.2 and Python 2.65) and something has changed. I... | I think your problem is this line:
```
content = file['content']
```
From the [Django docs](http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.FILES):
> Each value in FILES is an UploadedFile object containing the following attributes:
>
> * read(num\_bytes=None) -- Read a number of b... |
How to test if a dictionary contains certain keys | 3,415,347 | 6 | 2010-08-05T13:54:27Z | 3,415,398 | 20 | 2010-08-05T13:59:19Z | [
"python",
"dictionary"
] | Is there a nice approach to test if a dictionary contains multiple keys?
A short version of:
```
d = {}
if 'a' in d and 'b' in d and 'c' in d:
pass #do something
```
Thanks.
Edit: I can only use python2.4 -.- | ```
if all(test in d for test in ('a','b','c')):
# do something
``` |
How to test if a dictionary contains certain keys | 3,415,347 | 6 | 2010-08-05T13:54:27Z | 3,415,560 | 19 | 2010-08-05T14:15:20Z | [
"python",
"dictionary"
] | Is there a nice approach to test if a dictionary contains multiple keys?
A short version of:
```
d = {}
if 'a' in d and 'b' in d and 'c' in d:
pass #do something
```
Thanks.
Edit: I can only use python2.4 -.- | You can use `set.issubset(...)`, like so:
```
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> set(['a', 'b']).issubset(d)
True
>>> set(['a', 'x']).issubset(d)
False
```
---
Python 3 has introduced a set literal syntax which has been backported to Python 2.7, so these days the above can be written:
```
>>> d = {'a': 1, 'b': 2,... |
Removing elements from a list containing specific characters | 3,416,401 | 10 | 2010-08-05T15:35:41Z | 3,416,473 | 16 | 2010-08-05T15:43:06Z | [
"python",
"list",
"data-structures"
] | I want to remove all elements in a list which contains (or does not contain) a set of specific characters, however I'm running in to problems iterating over the list and removing elements as I go along. Two pretty much equal examples of this is given below. As you can see, if two elements which should be removed are di... | List comprehensions:
```
>>> l = ['1', '32', '523', '336']
>>> [ x for x in l if "2" not in x ]
['1', '336']
>>> [ x for x in l if "2" in x ]
['32', '523']
``` |
How to find all files in current directory with filenames that match a certain pattern in python? | 3,417,745 | 8 | 2010-08-05T18:08:04Z | 3,417,758 | 13 | 2010-08-05T18:09:33Z | [
"python"
] | I am trying to find all the files in the same directory as my script that has a filename matching a certain pattern. Ideally, I would like to store it in an array once I get them. The pattern I need to match is something like: `testing.JUNK.08-05.txt`. All the filenames have the testing in the front and end with the da... | Use the [`glob`](http://docs.python.org/library/glob.html) module:
```
import glob
for name in glob.glob('testing*08-05.txt'):
print name
``` |
How to sort a Python dict by value | 3,417,760 | 13 | 2010-08-05T18:09:40Z | 3,417,773 | 34 | 2010-08-05T18:11:39Z | [
"python",
"sorting",
"dictionary"
] | I have a dict that looks like this
`{ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }`
And I would like to convert it DESC and create a list of just the keywords. Eg, this would return
`["keyword3" , "keyword1" , "keyword4" , "keyword2"]`
**All examples I found use lambda and I'm not very strong with th... | You could use
```
res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))
```
(You don't need the `list` in Python 2.x)
The `theDict.__getitem__` is actually equivalent to `lambda x: theDict[x]`.
(A lambda is just an anonymous function. For example
```
>>> g = lambda x: x + 5
>>> g(123)
128
```
This is... |
How to sort a Python dict by value | 3,417,760 | 13 | 2010-08-05T18:09:40Z | 3,418,035 | 16 | 2010-08-05T18:43:49Z | [
"python",
"sorting",
"dictionary"
] | I have a dict that looks like this
`{ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }`
And I would like to convert it DESC and create a list of just the keywords. Eg, this would return
`["keyword3" , "keyword1" , "keyword4" , "keyword2"]`
**All examples I found use lambda and I'm not very strong with th... | ```
>>> d={ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }
>>> sorted(d, key=d.get, reverse=True)
['keyword3', 'keyword1', 'keyword4', 'keyword2']
``` |
month name to month number and vice versa in python | 3,418,050 | 34 | 2010-08-05T18:44:50Z | 3,418,092 | 33 | 2010-08-05T18:49:08Z | [
"python"
] | I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online.
I was thinking about the [calendar](http://docs.python.org/library/calendar.html) module. I see that to... | Creating a reverse dictionary would be a reasonable way to do this, because it's pretty simple:
```
import calendar
dict((v,k) for k,v in enumerate(calendar.month_abbr))
```
or in recent versions of Python (2.7+) which support dictionary comprehension:
```
{v: k for k,v in enumerate(calendar.month_abbr)}
``` |
month name to month number and vice versa in python | 3,418,050 | 34 | 2010-08-05T18:44:50Z | 5,158,964 | 37 | 2011-03-01T18:53:34Z | [
"python"
] | I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online.
I was thinking about the [calendar](http://docs.python.org/library/calendar.html) module. I see that to... | Just for fun:
```
from time import strptime
strptime('Feb','%b').tm_mon
``` |
month name to month number and vice versa in python | 3,418,050 | 34 | 2010-08-05T18:44:50Z | 21,938,128 | 10 | 2014-02-21T15:14:44Z | [
"python"
] | I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online.
I was thinking about the [calendar](http://docs.python.org/library/calendar.html) module. I see that to... | Here's yet another way to do it.
```
monthToNum(shortMonth):
return{
'Jan' : 1,
'Feb' : 2,
'Mar' : 3,
'Apr' : 4,
'May' : 5,
'Jun' : 6,
'Jul' : 7,
'Aug' : 8,
'Sep' : 9,
'Oct' : 10,
'Nov' : 11,
'Dec' : 12
}[shortMonth]
``` |
month name to month number and vice versa in python | 3,418,050 | 34 | 2010-08-05T18:44:50Z | 27,036,328 | 16 | 2014-11-20T09:46:15Z | [
"python"
] | I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online.
I was thinking about the [calendar](http://docs.python.org/library/calendar.html) module. I see that to... | Using [calendar](https://docs.python.org/2/library/calendar.html) module:
Number-to-Abbr
`calendar.month_abbr[month_number]`
Abbr-to-Number
`list(calendar.month_abbr).index(month_abbr)` |
Python: Unicode and ElementTree.parse | 3,418,262 | 10 | 2010-08-05T19:09:22Z | 12,345,506 | 12 | 2012-09-10T04:53:28Z | [
"python",
"xml",
"unicode",
"python-3.x"
] | I'm trying to move to Python 2.7 and since Unicode is a Big Deal there, I'd try dealing with them with XML files and texts and parse them using the `xml.etree.cElementTree` library. But I ran across this error:
```
>>> import xml.etree.cElementTree as ET
>>> from io import StringIO
>>> source = """\
... <?xml version=... | Your problem is that you are feeding `ElementTree` unicode, but it *prefers* to consume bytes. It will *provide* you with unicode in any case.
In Python 2.x, it can *only* consume bytes. You can tell it what encoding those bytes are in, but that's it. So, if you literally have to work with an object that represents a ... |
Execute python script inside a python script | 3,418,357 | 6 | 2010-08-05T19:20:58Z | 3,418,591 | 12 | 2010-08-05T19:49:17Z | [
"python"
] | I have a scenario where i want to dynamically generate a python script - inside my main python script - store it as a string and then when need be, execute this dynamically generated script from my main script.
Is this possible, if so how?
thanks | For a script in a file use exec
For a script in a string use eval
## !!! **But** !!!
before you use strings passed in from an external source, sanity check them!
Otherwise you expose the ability to execute arbitrary code from
within you program,
so **range check your variables!**
You do not ever want to be asking t... |
Appending values to dictionary in Python | 3,419,147 | 14 | 2010-08-05T21:04:50Z | 3,419,217 | 24 | 2010-08-05T21:15:13Z | [
"python",
"dictionary"
] | I have a dictionary to which I want to append to each drug, a list of numbers. Like this:
```
append(0), append(1234), append(123), etc.
def make_drug_dictionary(data):
drug_dictionary={'MORPHINE':[],
'OXYCODONE':[],
'OXYMORPHONE':[],
'METHADONE':[],
... | Just use append:
```
list1=[1,2,3,4,5]
list2=[123,234,456]
d={'a':[],'b':[]}
d['a'].append(list1)
d['a'].append(list2)
print d['a']
``` |
Appending values to dictionary in Python | 3,419,147 | 14 | 2010-08-05T21:04:50Z | 3,419,315 | 9 | 2010-08-05T21:28:28Z | [
"python",
"dictionary"
] | I have a dictionary to which I want to append to each drug, a list of numbers. Like this:
```
append(0), append(1234), append(123), etc.
def make_drug_dictionary(data):
drug_dictionary={'MORPHINE':[],
'OXYCODONE':[],
'OXYMORPHONE':[],
'METHADONE':[],
... | You should use append to add to the list. But also here are few code tips:
I would use `dict.setdefault` or `defaultdict` to avoid having to specify the empty list in the dictionary definition.
If you use `prev` to to filter out duplicated values you can simplfy the code using `groupby` from `itertools`
Your code wit... |
Generator in if-statement in python | 3,419,528 | 4 | 2010-08-05T21:56:09Z | 3,419,563 | 7 | 2010-08-05T22:02:09Z | [
"python",
"list",
"if-statement",
"generator",
"list-comprehension"
] | **Or How to if-statement in a modified list.**
I've been reading StackOverflow for a while (thanks to everyone). I love it. I also seen that you can post a question and answer it yourself. Sorry if I duplicate, but I didn't found this particular answer on StackOverflow.
---
* How do you verify if a element is in a l... | ```
if any(s.lower() == "foo" for s in list): print "found"
``` |
Print to the same line and not a new line in python | 3,419,984 | 32 | 2010-08-05T23:36:20Z | 3,419,991 | 51 | 2010-08-05T23:38:16Z | [
"python",
"stdout"
] | Basically I want to do the opposite of what this guy did... hehe.
<http://stackoverflow.com/questions/529395/python-script-print-new-line-each-time-to-shell-rather-than-update-existing-line>
I have a program that is telling me how far along it is.
```
for i in some_list:
#do a bunch of stuff.
print i/len(som... | It's called the carriage return, or `\r`
Use
```
print i/len(some_list)*100," percent complete \r",
```
The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)
Also, don't forget to terminate with a `print ""` to get at least a finalizing newline! |
Print to the same line and not a new line in python | 3,419,984 | 32 | 2010-08-05T23:36:20Z | 7,464,288 | 13 | 2011-09-18T20:37:06Z | [
"python",
"stdout"
] | Basically I want to do the opposite of what this guy did... hehe.
<http://stackoverflow.com/questions/529395/python-script-print-new-line-each-time-to-shell-rather-than-update-existing-line>
I have a program that is telling me how far along it is.
```
for i in some_list:
#do a bunch of stuff.
print i/len(som... | From python 3.x you can do:
```
print('bla bla', end='')
```
(which can also be used in Python 2.6 or 2.7 by putting `from __future__ import print_function` at the top of your script/module)
**Python console progressbar example:**
```
import time
# status generator
def range_with_status(total):
""" iterate fro... |
Print to the same line and not a new line in python | 3,419,984 | 32 | 2010-08-05T23:36:20Z | 15,607,115 | 8 | 2013-03-25T03:25:09Z | [
"python",
"stdout"
] | Basically I want to do the opposite of what this guy did... hehe.
<http://stackoverflow.com/questions/529395/python-script-print-new-line-each-time-to-shell-rather-than-update-existing-line>
I have a program that is telling me how far along it is.
```
for i in some_list:
#do a bunch of stuff.
print i/len(som... | for Console you'll probably need
```
sys.stdout.flush()
```
to force update. I think using `,` in print will block stdout from flushing and somehow it won't update |
Creating a dynamic choice field | 3,419,997 | 92 | 2010-08-05T23:39:55Z | 3,420,072 | 8 | 2010-08-05T23:57:24Z | [
"python",
"django",
"django-forms",
"django-templates"
] | I'm having some trouble trying to understand how to create a dynamic choice field in django. I have a model set up something like:
```
class rider(models.Model):
user = models.ForeignKey(User)
waypoint = models.ManyToManyField(Waypoint)
class Waypoint(models.Model):
lat = models.FloatField()
lng =... | There's built-in solution for your problem: [ModelChoiceField](https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield).
Generally, it's always worth trying to use `ModelForm` when you need to create/change database objects. Works in 95% of the cases and it's much cleaner than creating your own implem... |
Creating a dynamic choice field | 3,419,997 | 92 | 2010-08-05T23:39:55Z | 3,420,588 | 138 | 2010-08-06T02:17:36Z | [
"python",
"django",
"django-forms",
"django-templates"
] | I'm having some trouble trying to understand how to create a dynamic choice field in django. I have a model set up something like:
```
class rider(models.Model):
user = models.ForeignKey(User)
waypoint = models.ManyToManyField(Waypoint)
class Waypoint(models.Model):
lat = models.FloatField()
lng =... | you can filter the waypoints by passing the user to the form init
```
class waypointForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(
choices=[(o.id, str(o)) for o in Waypoint.ob... |
Creating a dynamic choice field | 3,419,997 | 92 | 2010-08-05T23:39:55Z | 5,139,054 | 7 | 2011-02-28T06:59:07Z | [
"python",
"django",
"django-forms",
"django-templates"
] | I'm having some trouble trying to understand how to create a dynamic choice field in django. I have a model set up something like:
```
class rider(models.Model):
user = models.ForeignKey(User)
waypoint = models.ManyToManyField(Waypoint)
class Waypoint(models.Model):
lat = models.FloatField()
lng =... | the problem is when you do
```
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)])
```
in a update request, the previous value will lost! |
wxPython: How to make a TextCtrl fill a Panel | 3,420,021 | 4 | 2010-08-05T23:44:50Z | 3,420,058 | 8 | 2010-08-05T23:54:55Z | [
"python",
"wxpython"
] | How do I set the size of a multi-line TextCtrl to always fill its parent panel? | Use a `boxSizer`.
When you add your `textCtrl` to the sizer set the proportion to `1` and pass the `wx.EXPAND` flag, that way your `textCtrl` should fill the panel even when the panel is resized
```
bsizer = wx.BoxSizer()
bsizer.Add(yourTxtCtrl, 1, wx.EXPAND)
```
Put the following at the end of your panels initializ... |
How do I use Mox to mock a module function and allow it to be called in almost any way | 3,420,111 | 4 | 2010-08-06T00:06:23Z | 12,414,889 | 8 | 2012-09-13T21:14:18Z | [
"python",
"mox"
] | I have a function A that call another function B several times. I want to mock B in such a way that *any number* of calls that have the correct number of arguments, regardless of value, will return a fixed vale and be treated as correct.
If or how many times the the function is called is not a part of the spec. | Stub out B normally....
Assuming B accepts 2 arguments and should return 'foo':
```
B(mox.IgnoreArg(), mox.IgnoreArg()).MultipleTimes().AndReturn('foo')
``` |
Filter dict to contain only certain keys? | 3,420,122 | 176 | 2010-08-06T00:08:36Z | 3,420,133 | 40 | 2010-08-06T00:13:39Z | [
"python"
] | I've got a `dict` that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out? | Here's an example in python 2.6:
```
>>> a = {1:1, 2:2, 3:3}
>>> dict((key,value) for key, value in a.iteritems() if key == 1)
{1: 1}
```
The filtering part is the `if` statement.
This method is slower than delnan's answer if you only want to select a few of very many keys. |
Filter dict to contain only certain keys? | 3,420,122 | 176 | 2010-08-06T00:08:36Z | 3,420,156 | 235 | 2010-08-06T00:22:21Z | [
"python"
] | I've got a `dict` that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out? | Constructing a new dict:
```
dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }
```
Uses dictionary comprehension.
If you use a version which lacks them (ie Python 2.6 and earlier), make it `dict((your_key, old_dict[your_key]) for ...)`. It's the same, though uglier.
Note that this, unlike j... |
Filter dict to contain only certain keys? | 3,420,122 | 176 | 2010-08-06T00:08:36Z | 3,420,253 | 9 | 2010-08-06T00:49:04Z | [
"python"
] | I've got a `dict` that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out? | Given your original dictionary `orig` and the set of entries that you're interested in `keys`:
```
filtered = dict(zip(keys, [orig[k] for k in keys]))
```
which isn't as nice as delnan's answer, but should work in every Python version of interest. It is, however, fragile to each element of `keys` existing in your ori... |
Filter dict to contain only certain keys? | 3,420,122 | 176 | 2010-08-06T00:08:36Z | 22,975,080 | 31 | 2014-04-09T22:21:29Z | [
"python"
] | I've got a `dict` that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out? | Slightly more elegant dict comprehension:
```
foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}
``` |
What's better, ConfigObj or ConfigParser? | 3,420,250 | 22 | 2010-08-06T00:48:32Z | 4,476,200 | 16 | 2010-12-18T02:00:18Z | [
"python",
"configparser",
"configobj"
] | Which is better for creating a settings file for Python programs, the built-in module ([ConfigParser](http://docs.python.org/library/configparser.html#module-ConfigParser)), or the independent project ([ConfigObj](http://www.voidspace.org.uk/python/configobj.html))? | I recently switched from configparser to configobj, and I'm thrilled to have done so.
For me, the big difference is configobj's [validator](https://configobj.readthedocs.io/en/latest/validate.html). It lets me very easily/succinctly (1) define the type and acceptable values for each entry, and (2) set defaults.
Those... |
Python vs C#/.NET -- what are the key differences to consider for using one to develop a large web application? | 3,420,594 | 39 | 2010-08-06T02:18:54Z | 3,420,674 | 30 | 2010-08-06T02:41:46Z | [
".net",
"python",
"sql-server",
"django",
"asp.net-mvc-2"
] | My organization currently delivers a web application primarily based on a SQL Server 2005/2008 back end, a framework of Java models/controllers, and ColdFusion-based views. We have decided to transition to a newer framework and after internal explorations and mini projects have narrowed the choice down to between Pytho... | ".NET" is not a language. Perhaps it's Python vs. C# or Python/Django vs C#/ASP.NET (or pick whatever "webwork" you want; there are many, many different solutions for both Python and ".NET" and picking Django or MVC2 of the bat might severely limiting better viable options). As a counter to the Python vs. ".NET": There... |
Python vs C#/.NET -- what are the key differences to consider for using one to develop a large web application? | 3,420,594 | 39 | 2010-08-06T02:18:54Z | 16,702,977 | 19 | 2013-05-22T23:04:22Z | [
".net",
"python",
"sql-server",
"django",
"asp.net-mvc-2"
] | My organization currently delivers a web application primarily based on a SQL Server 2005/2008 back end, a framework of Java models/controllers, and ColdFusion-based views. We have decided to transition to a newer framework and after internal explorations and mini projects have narrowed the choice down to between Pytho... | I wrote a very comprehensive answer on Quora about this: [How does Python compare to C#?](http://qr.ae/pvRDm)
> TL;DR
>
> * The answer is huge, but (hopefully) quite comprehensive. I programmed on C# / .NET for almost 10 years, so I know it really well. And I program on Python at Quora for ~ 7 months now, so I hope I ... |
Multilingual flask application | 3,420,897 | 12 | 2010-08-06T03:53:46Z | 3,427,586 | 16 | 2010-08-06T20:34:03Z | [
"python",
"localization",
"internationalization",
"flask",
"multilanguage"
] | Is there a preferred way to make a Flask application multilingual? Ideally, the solution would enable to `@app.route` the same view to use different urls for each languages, like `@app.route(en='/staff/', fr='/equipe/)`. I'm pretty confident I could hack something like that together, but an existing library would sure ... | I believe that [Flask-Babel](http://packages.python.org/Flask-Babel/) is what you are looking for. |
Algorithm to find which number in a list sum up to a certain number | 3,420,937 | 14 | 2010-08-06T04:09:50Z | 3,421,173 | 24 | 2010-08-06T05:16:57Z | [
"python",
"algorithm",
"math",
"pseudocode"
] | I have a list of numbers. I also have a certain sum. The sum is made from a few numbers from my list (I may/may not know how many numbers it's made from). Is there a fast algorithm to get a list of possible numbers? Written in Python would be great, but pseudo-code's good too. (I can't yet read anything other than Pyth... | This problem reduces to the [0-1 Knapsack Problem](http://en.wikipedia.org/wiki/Knapsack_problem), where you are trying to find a set with an exact sum. The solution depends on the constraints, in the general case this problem is NP-Complete.
However, if the maximum search sum (let's call it `S`) is not too high, then... |
Simple protocols (like twisted.pb) vs messaging (AMQP/JMS) vs web services (REST/SOAP) | 3,421,200 | 4 | 2010-08-06T05:27:01Z | 3,426,017 | 12 | 2010-08-06T17:03:03Z | [
"python",
"web-services",
"twisted",
"network-protocols",
"amqp"
] | I'm currently using twisted's perspective broker on python and I have considered in the past switching to something like RabbitMQ but I'm not sure it could just replace pb - I feel like I might be comparing apples to oranges here.
I've been reading a lot about REST lately and the inevitable debate with SOAP, which led ... | As always, "it depends". First, let's clear up the terminology.
Twisted's *Perspective Broker* basically is a system you can use when you have control over both ends of a distributed action (both client and server ends). It provides a way to copy objects from one end to the other and to call methods on remote objects.... |
Python: "global name 'time' is not defined" | 3,421,290 | 8 | 2010-08-06T05:48:12Z | 3,421,366 | 16 | 2010-08-06T06:05:34Z | [
"python",
"time"
] | I'm writing a silly program in python for a friend that prints "We are the knights who say 'Ni'!". then sleeps for 3 seconds, and then prints "Ni!" twenty times at random intervals using the `random` module's `uniform()` method. Here's my code:
```
from time import sleep
import random
def knights_of_ni():
generat... | That's impossible. Your code example isn't the same as the code that produced that error.
Perhaps you had `time.sleep(..)` instead of `sleep(..)`. You have done `from time import sleep`. To use the `time.sleep(..)` form you must `import time` |
What exactly does a non-shallow filecmp.cmp do? | 3,421,523 | 4 | 2010-08-06T06:38:32Z | 3,421,525 | 7 | 2010-08-06T06:38:48Z | [
"python",
"filecompare"
] | I'm using Python 2.6.2. The [docs for the filecmp module](http://docs.python.org/release/2.6.5/library/filecmp.html) say:
> The filecmp module defines functions to compare files and directories, with various optional time/correctness trade-offs.
and, of the filecmp.cmp function:
> filecmp.cmp(f1, f2[, shallow])
>
> ... | Consulting the [source `filecmp.py`](http://hg.python.org/cpython/file/2.7/Lib/filecmp.py) reveals that if `shallow=False`, `filecmp.cmp` does an exact contents comparison by reading and comparing chunks of each file. It returns `True` only if the two files have exactly the same contents. |
How to merge lists of dictionaries | 3,421,906 | 6 | 2010-08-06T07:52:34Z | 3,422,287 | 13 | 2010-08-06T08:56:01Z | [
"python"
] | With lists of dictionaries such as the following:
```
user_course_score = [
{'course_id': 1456, 'score': 56},
{'course_id': 316, 'score': 71}
]
courses = [
{'course_id': 1456, 'name': 'History'},
{'course_id': 316, 'name': 'Science'},
{'course_id': 926, 'name': 'Geography'}
]
```
What is the be... | Here's a possible solution:
```
def merge_lists(l1, l2, key):
merged = {}
for item in l1+l2:
if item[key] in merged:
merged[item[key]].update(item)
else:
merged[item[key]] = item
return merged.values()
courses = merge_lists(user_course_score, courses, 'course_id')
`... |
What is Python buffer type for? | 3,422,685 | 105 | 2010-08-06T09:55:44Z | 3,422,740 | 105 | 2010-08-06T10:05:04Z | [
"python",
"python-2.7"
] | There is a `buffer` type in python, but I don't know how can I use it.
In the [Python doc](http://docs.python.org/library/functions.html#buffer) the description is:
> `buffer(object[, offset[, size]])`
>
> The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buff... | An example usage:
```
>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world
```
The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the stri... |
What is Python buffer type for? | 3,422,685 | 105 | 2010-08-06T09:55:44Z | 3,427,320 | 18 | 2010-08-06T19:59:34Z | [
"python",
"python-2.7"
] | There is a `buffer` type in python, but I don't know how can I use it.
In the [Python doc](http://docs.python.org/library/functions.html#buffer) the description is:
> `buffer(object[, offset[, size]])`
>
> The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buff... | I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains `buffer` in [this mailinglist post](http://mail.python.org/pipermail/python-dev/2000-October/009974.html)).
For example, numpy seems to use buffer for efficient data storage:
```
import numpy
a = numpy.ndarray(1000... |
Which Actor model library/framework for python and Erlang-like? | 3,423,447 | 33 | 2010-08-06T11:47:58Z | 3,435,125 | 17 | 2010-08-08T16:36:53Z | [
"python",
"erlang",
"actor",
"python-stackless"
] | I am looking for an easy-to-learn Actor library or framework for Python 2.x. I have tried Candygram and Twisted but I did not like them. I'd like something that will be easy to extend to suppero Greenlet (= stackless python).
* Candygram is too old.
* Twisted is too complicated.
* Gevent: it is unclear if it can suppo... | To make actors with [gevent](http://www.gevent.org), use a [Greenlet](http://www.gevent.org/gevent.html#greenlet-objects) subclass with embedded [gevent.queue.Queue](http://www.gevent.org/gevent.queue.html) instance used as an inbox. To read a message from the inbox, simply [get()](http://www.gevent.org/gevent.queue.ht... |
Which Actor model library/framework for python and Erlang-like? | 3,423,447 | 33 | 2010-08-06T11:47:58Z | 18,219,655 | 11 | 2013-08-13T21:36:56Z | [
"python",
"erlang",
"actor",
"python-stackless"
] | I am looking for an easy-to-learn Actor library or framework for Python 2.x. I have tried Candygram and Twisted but I did not like them. I'd like something that will be easy to extend to suppero Greenlet (= stackless python).
* Candygram is too old.
* Twisted is too complicated.
* Gevent: it is unclear if it can suppo... | Check out [pulsar](http://quantmind.github.io/pulsar/index.html), it is a concurrent framework for python which uses the actor model as source of parallel execution. |
python 2.7 / exec / what is wrong? | 3,423,601 | 5 | 2010-08-06T12:10:26Z | 3,423,935 | 12 | 2010-08-06T12:57:21Z | [
"python",
"redirect",
"exec",
"stdio",
"stringio"
] | I have this code which runs fine in Python 2.5 but not in 2.7:
```
import sys
import traceback
try:
from io import StringIO
except:
from StringIO import StringIO
def CaptureExec(stmt):
oldio = (sys.stdin, sys.stdout, sys.stderr)
sio = StringIO()
sys.stdout = sys.stderr = sio
try:
exec(... | `io.StringIO` is confusing in Python 2.7 because it's backported from the 3.x bytes/string world. This code gets the same error as yours:
```
from io import StringIO
sio = StringIO()
sio.write("Hello\n")
```
causes:
```
Traceback (most recent call last):
File "so2.py", line 3, in <module>
sio.write("Hello\n")
... |
Using IPython from the Python shell like `code.interact()` | 3,423,741 | 14 | 2010-08-06T12:30:49Z | 8,152,484 | 17 | 2011-11-16T13:32:37Z | [
"python",
"shell",
"ipython"
] | Is it possible to use the IPython shell from an existing Python shell, as a shell-inside-a-shell, similarly to the built-in `code.interact()`? | In **IPython 0.11** the API has been overhauled and the shell is even easier to invoke:
```
import IPython
IPython.embed()
``` |
Getting ready to convert from Python 2.x to 3.x | 3,424,292 | 10 | 2010-08-06T13:36:29Z | 3,424,843 | 12 | 2010-08-06T14:41:32Z | [
"python",
"python-3.x",
"upgrade",
"python-2.x"
] | As we all know by now (I hope), Python 3 is slowly beginning to replace Python 2.x. Of course it will be many MANY years before most of the existing code is finally ported, but there are things we can do right now in our version 2.x code to make the switch easier.
Obviously taking a look at [what's new](http://docs.py... | The biggest problem that cannot be adequately addressed by micro-level changes and 2to3 is the change of the default string type from bytes to Unicode.
If your code needs to do anything with encodings and byte I/O, it's going to need a bunch of manual effort to convert correctly, so that things that have to be bytes r... |
Python: how to change (last) element of tuple? | 3,424,507 | 7 | 2010-08-06T14:03:26Z | 3,424,534 | 16 | 2010-08-06T14:07:15Z | [
"python"
] | The question is a bit misleading, because a tuple is *immutable*. What I want is:
Having a tuple `a = (1, 2, 3, 4)` get a tuple `b` that is exactly like `a` except for the last argument which is, say, twice the last element of `a`.
=> b == (1, 2, 3, 8) | ```
b = a[:-1] + (a[-1]*2,)
```
What I'm doing here is concatenation of two tuples, the first containing everything but the last element, and a new tuple containing the mutation of the final element. The result is a new tuple containing what you want.
Note that for `+` to return a tuple, both operands must be a tuple... |
Is twisted.internet.reactor global? | 3,424,825 | 6 | 2010-08-06T14:39:50Z | 3,424,862 | 12 | 2010-08-06T14:43:32Z | [
"python",
"networking",
"twisted",
"reactor"
] | For example, if one application does `from twisted.internet import reactor`, and another application does the same, are those `reactors` the same?
I am asking because [Deluge](http://deluge-torrent.org/), an application that uses twisted, looks like it uses the reactor to connect their UI (gtk) to the rest of the appl... | Yes, every module in Python is always global, or, to put it better, a singleton: when you do `from twisted.internet import reactor`, Python's import mechanism first checks `sys.modules['twisted.internet.reactor']`, and, if that exists, returns said value; only if it doesn't exist (i.e., the first time a module is impor... |
What's the simplest way to subtract a month from a date in Python? | 3,424,899 | 19 | 2010-08-06T14:48:49Z | 3,425,016 | 11 | 2010-08-06T15:01:47Z | [
"python"
] | If only timedelta had a month argument in it's constructor. So what's the simplest way to do this?
**EDIT:** I wasn't thinking too hard about this as was pointed out below. Really what I wanted was any day in the last month because eventually I'm going to grab the year and month only. So given a datetime object, what'... | > If only timedelta had a month argument
> in it's constructor. So what's the
> simplest way to do this?
What do you want the result to be when you subtract a month from, say, a date that is March 30? That is the problem with adding or subtracting months: months have different lengths! In some application an exception... |
What's the simplest way to subtract a month from a date in Python? | 3,424,899 | 19 | 2010-08-06T14:48:49Z | 3,425,124 | 16 | 2010-08-06T15:13:01Z | [
"python"
] | If only timedelta had a month argument in it's constructor. So what's the simplest way to do this?
**EDIT:** I wasn't thinking too hard about this as was pointed out below. Really what I wanted was any day in the last month because eventually I'm going to grab the year and month only. So given a datetime object, what'... | Try this:
```
def monthdelta(date, delta):
m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
if not m: m = 12
d = min(date.day, [31,
29 if y%4==0 and not y%400==0 else 28,31,30,31,30,31,31,30,31,30,31][m-1])
return date.replace(day=d,month=m, year=y)
>>> for m in range(-... |
What's the simplest way to subtract a month from a date in Python? | 3,424,899 | 19 | 2010-08-06T14:48:49Z | 7,153,449 | 15 | 2011-08-22T20:50:53Z | [
"python"
] | If only timedelta had a month argument in it's constructor. So what's the simplest way to do this?
**EDIT:** I wasn't thinking too hard about this as was pointed out below. Really what I wanted was any day in the last month because eventually I'm going to grab the year and month only. So given a datetime object, what'... | After the original question's edit to "any datetime object in the previous month", you can do it pretty easily by subtracting 1 day from the first of the month.
```
from datetime import datetime, timedelta
def a_day_in_previous_month(dt):
return datetime(dt.year, dt.month, 1) - timedelta(days=1)
``` |
What's the simplest way to subtract a month from a date in Python? | 3,424,899 | 19 | 2010-08-06T14:48:49Z | 14,459,459 | 65 | 2013-01-22T13:16:54Z | [
"python"
] | If only timedelta had a month argument in it's constructor. So what's the simplest way to do this?
**EDIT:** I wasn't thinking too hard about this as was pointed out below. Really what I wanted was any day in the last month because eventually I'm going to grab the year and month only. So given a datetime object, what'... | You can use the third party [`dateutil`](https://labix.org/python-dateutil) module (PyPI entry [here](https://pypi.python.org/pypi/python-dateutil)).
```
import datetime
import dateutil.relativedelta
d = datetime.datetime.strptime("2013-03-31", "%Y-%m-%d")
d2 = d - dateutil.relativedelta.relativedelta(months=1)
print... |
A simpler i18n for Python/Django | 3,424,939 | 2 | 2010-08-06T14:54:04Z | 3,426,006 | 12 | 2010-08-06T17:01:35Z | [
"python",
"django",
"internationalization"
] | My question is regarding i18n in Python. From what I understand, it involves:
* Create a messages file per language (ONLY ONE?!).
* in this file, each message will be of the format
+ `English message here`
+ `Message en Francais ici` (yea crappy french..)
* then have this file compiled into another faster binary f... | While you could do this fairly simply, I would question why.
As is:
1. Django's i18n is based around `gettext`, which has never given me any performance problems.
2. You don't have to create the message file, Django will [do it for you](http://docs.djangoproject.com/en/dev/topics/i18n/localization/#how-to-create-lang... |
How to detect the OS default language in python? | 3,425,294 | 9 | 2010-08-06T15:31:05Z | 3,425,316 | 12 | 2010-08-06T15:33:36Z | [
"python"
] | Is there any universal method to detect the OS default language? (regardless what is the OS that is running the code)
```
import os
os.getenv('LANG')
```
The above code works under Linux, does it work under other OS? | You could use the [`getdefaultlocale` function in the `locale` module](http://docs.python.org/library/locale.html#locale.getdefaultlocale). It returns the language code and encoding of the system default locale in a tuple:
```
>>> import locale
>>> locale.getdefaultlocale()
('en_GB', 'cp1252')
``` |
sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings | 3,425,320 | 69 | 2010-08-06T15:34:24Z | 3,425,465 | 31 | 2010-08-06T15:50:34Z | [
"python",
"unicode",
"sqlite3",
"zlib"
] | Using SQLite3 in Python, I am trying to store a compressed version of a snippet of UTF-8 HTML code.
Code looks like this:
```
...
c = connection.cursor()
c.execute('create table blah (cid integer primary key,html blob)')
...
c.execute('insert or ignore into blah values (?, ?)',(cid, zlib.compress(html)))
```
At whic... | Found the solution, I should have spent just a little more time searching.
Solution is to 'cast' the value as a Python 'buffer', like so:
```
c.execute('insert or ignore into blah values (?, ?)',(cid, buffer(zlib.compress(html))))
```
Hopefully this will help somebody else. |
sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings | 3,425,320 | 69 | 2010-08-06T15:34:24Z | 4,020,598 | 69 | 2010-10-26T03:59:17Z | [
"python",
"unicode",
"sqlite3",
"zlib"
] | Using SQLite3 in Python, I am trying to store a compressed version of a snippet of UTF-8 HTML code.
Code looks like this:
```
...
c = connection.cursor()
c.execute('create table blah (cid integer primary key,html blob)')
...
c.execute('insert or ignore into blah values (?, ?)',(cid, zlib.compress(html)))
```
At whic... | If you want to use 8-bit strings instead of unicode string in sqlite3, set approptiate text\_factory for sqlite connection:
```
connection = sqlite3.connect(...)
connection.text_factory = str
``` |
sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings | 3,425,320 | 69 | 2010-08-06T15:34:24Z | 24,655,777 | 23 | 2014-07-09T14:00:53Z | [
"python",
"unicode",
"sqlite3",
"zlib"
] | Using SQLite3 in Python, I am trying to store a compressed version of a snippet of UTF-8 HTML code.
Code looks like this:
```
...
c = connection.cursor()
c.execute('create table blah (cid integer primary key,html blob)')
...
c.execute('insert or ignore into blah values (?, ?)',(cid, zlib.compress(html)))
```
At whic... | In order to work with the BLOB type, you must first convert your zlib compressed string into binary data - otherwise sqlite will try to process it as a text string. This is done with sqlite3.Binary(). For example:
`c.execute('insert or ignore into blah values (?, ?)',(cid, sqlite3.Binary(zlib.compress(html))))` |
Why does corrcoef return a matrix? | 3,425,439 | 8 | 2010-08-06T15:47:09Z | 3,425,496 | 16 | 2010-08-06T15:53:43Z | [
"python",
"math",
"numpy"
] | It seems strange to me that np.corrcoef returns a matrix.
```
correlation1 = corrcoef(Strategy1Returns,Strategy2Returns)
[[ 1. -0.99598935]
[-0.99598935 1. ]]
```
Does anyone know why this is the case and whether it is possible to return just one value in the classical sense? | [`corrcoef`](http://www.scipy.org/Numpy_Example_List_With_Doc#corrcoef) returns the normalised covariance matrix.
The covariance matrix is the matrix
```
Cov( X, X ) Cov( X, Y )
Cov( Y, X ) Cov( Y, Y )
```
Normalised, this will yield the matrix:
```
Corr( X, X ) Corr( X, Y )
Corr( Y, X ) Corr( Y, Y )
... |
Why does corrcoef return a matrix? | 3,425,439 | 8 | 2010-08-06T15:47:09Z | 3,425,548 | 20 | 2010-08-06T15:58:43Z | [
"python",
"math",
"numpy"
] | It seems strange to me that np.corrcoef returns a matrix.
```
correlation1 = corrcoef(Strategy1Returns,Strategy2Returns)
[[ 1. -0.99598935]
[-0.99598935 1. ]]
```
Does anyone know why this is the case and whether it is possible to return just one value in the classical sense? | It allows you to compute correlation coefficients of >2 data sets, e.g.
```
>>> from numpy import *
>>> a = array([1,2,3,4,6,7,8,9])
>>> b = array([2,4,6,8,10,12,13,15])
>>> c = array([-1,-2,-2,-3,-4,-6,-7,-8])
>>> corrcoef([a,b,c])
array([[ 1. , 0.99535001, -0.9805214 ],
[ 0.99535001, 1. , -0.9... |
How do I get the same functionality as C's __FUNCTION__ in Python? | 3,425,512 | 4 | 2010-08-06T15:55:48Z | 3,425,585 | 9 | 2010-08-06T16:03:53Z | [
"python",
"function"
] | In C, I can put a log printf inside a function like this:
```
void xx_lock (int xx_flag)
{
printf ("%s: START with %d\n", __FUNCTION__, xx_flag);
}
```
so I can copy the same line where I need in any function and it displays the function name in the log. I want something similar in Python. But if I use
```
__name_... | What you've asked for can't be done (nicely -- there are ways of doing it but they are nasty hacks). BUT: you don't really want to do that. Think at a higher level: you want an easy way to modify a function to log that it has started. Changing the *source code* of the function isn't a good way do to that -- after all, ... |
How do I get the same functionality as C's __FUNCTION__ in Python? | 3,425,512 | 4 | 2010-08-06T15:55:48Z | 3,425,814 | 7 | 2010-08-06T16:35:49Z | [
"python",
"function"
] | In C, I can put a log printf inside a function like this:
```
void xx_lock (int xx_flag)
{
printf ("%s: START with %d\n", __FUNCTION__, xx_flag);
}
```
so I can copy the same line where I need in any function and it displays the function name in the log. I want something similar in Python. But if I use
```
__name_... | katrielalex above is right that you should not attempt to do this the "C way". Python has batteries included, so why not use them?
```
import logging, sys
logging.basicConfig(format="%(filename)s:%(funcName)s:%(message)s",level=logging.DEBUG,stream=sys.stderr)
def testFunc():
logging.debug("entering")
testFunc(... |
How to search through a gtk.ListStore in pyGTK and remove elements? | 3,426,106 | 2 | 2010-08-06T17:16:53Z | 3,432,058 | 9 | 2010-08-07T21:11:45Z | [
"python",
"gtk",
"pygtk"
] | I have the following code (where store is a `gtk.ListStore` and titer is a `gtk.TreeIter`. The docs say that if there is no next row, `iter_next()` will return `None`, hence the break when that is found. It is supposed to search through the `ListStore` of `(int, str)` and remove the one item whose `int` component match... | The only mistake I notice is `store.get_path(titer)[0]`, which will just get the row number of the list model. It should be `store.get_value(titer, 0)`.
By the way, your code can be expressed in a simpler style using the (PyGTK-only) [TreeModelRow](http://www.pygtk.org/docs/pygtk/class-pygtktreemodelrow.html):
```
fo... |
Numeric Sort in Python | 3,426,108 | 31 | 2010-08-06T17:17:26Z | 3,426,120 | 21 | 2010-08-06T17:18:39Z | [
"python",
"sorting"
] | I know that this sounds trivial but I did not realize that the `sort()` function of Python was weird. I have a list of "numbers" that are actually in string form, so I first convert them to ints, then attempt a sort.
```
list1=["1","10","3","22","23","4","2","200"]
for item in list1:
item=int(item)
list1.sort()
p... | You could pass a function to the `key` parameter to [the `.sort` method](http://docs.python.org/library/stdtypes.html#mutable-sequence-types). With this, the system will sort by key(x) instead of x.
```
list1.sort(key=int)
```
---
BTW, to convert the list to integers permanently, use [the `map` function](http://docs... |
Numeric Sort in Python | 3,426,108 | 31 | 2010-08-06T17:17:26Z | 3,426,155 | 76 | 2010-08-06T17:22:23Z | [
"python",
"sorting"
] | I know that this sounds trivial but I did not realize that the `sort()` function of Python was weird. I have a list of "numbers" that are actually in string form, so I first convert them to ints, then attempt a sort.
```
list1=["1","10","3","22","23","4","2","200"]
for item in list1:
item=int(item)
list1.sort()
p... | You haven't actually converted your strings to ints. Or rather, you did, but then you didn't do anything with the results. What you want is:
```
list1 = ["1","10","3","22","23","4","2","200"]
list1 = [int(x) for x in list1]
list1.sort()
```
However, python makes it even easier for you: sort takes a named parameter, k... |
Numeric Sort in Python | 3,426,108 | 31 | 2010-08-06T17:17:26Z | 3,426,157 | 8 | 2010-08-06T17:22:35Z | [
"python",
"sorting"
] | I know that this sounds trivial but I did not realize that the `sort()` function of Python was weird. I have a list of "numbers" that are actually in string form, so I first convert them to ints, then attempt a sort.
```
list1=["1","10","3","22","23","4","2","200"]
for item in list1:
item=int(item)
list1.sort()
p... | Python's sort isn't weird. It's just that this code:
```
for item in list1:
item=int(item)
```
isn't doing what you think it is - `item` is not replaced back into the list, it is simply thrown away.
Anyway, the correct solution is to use `key=int` as others have shown you. |
Numeric Sort in Python | 3,426,108 | 31 | 2010-08-06T17:17:26Z | 14,074,039 | 8 | 2012-12-28T18:28:55Z | [
"python",
"sorting"
] | I know that this sounds trivial but I did not realize that the `sort()` function of Python was weird. I have a list of "numbers" that are actually in string form, so I first convert them to ints, then attempt a sort.
```
list1=["1","10","3","22","23","4","2","200"]
for item in list1:
item=int(item)
list1.sort()
p... | In case you want to use [`sorted()`](https://docs.python.org/2/library/functions.html#sorted) function: `sorted(list1, key=int)`
It returns a new sorted list. |
Calculating Time Difference | 3,426,870 | 19 | 2010-08-06T19:01:57Z | 3,426,953 | 9 | 2010-08-06T19:11:25Z | [
"python",
"time"
] | at the start and end of my program, I have
```
from time import strftime
print int(strftime("%Y-%m-%d %H:%M:%S")
Y1=int(strftime("%Y"))
m1=int(strftime("%m"))
d1=int(strftime("%d"))
H1=int(strftime("%H"))
M1=int(strftime("%M"))
S1=int(strftime("%S"))
Y2=int(strftime("%Y"))
m2=int(strftime("%m"))
d2=int(strftime("... | ```
from time import time
start_time = time()
...
end_time = time()
time_taken = end_time - starttime # time_taken is in seconds
hours, rest = divmod(time_taken,3600)
minutes, seconds = divmod(rest, 60)
``` |
Calculating Time Difference | 3,426,870 | 19 | 2010-08-06T19:01:57Z | 3,427,051 | 50 | 2010-08-06T19:24:58Z | [
"python",
"time"
] | at the start and end of my program, I have
```
from time import strftime
print int(strftime("%Y-%m-%d %H:%M:%S")
Y1=int(strftime("%Y"))
m1=int(strftime("%m"))
d1=int(strftime("%d"))
H1=int(strftime("%H"))
M1=int(strftime("%M"))
S1=int(strftime("%S"))
Y2=int(strftime("%Y"))
m2=int(strftime("%m"))
d2=int(strftime("... | The [`datetime`](http://docs.python.org/library/datetime) module will do all the work for you:
```
>>> import datetime
>>> a = datetime.datetime.now()
>>> # ...wait a while...
>>> b = datetime.datetime.now()
>>> print(b-a)
0:03:43.984000
```
If you don't want to display the microseconds, just use (as gnibbler suggest... |
is there a better way to hold this data then a dictionary of dictionaries of dictionaries? python | 3,427,198 | 2 | 2010-08-06T19:43:52Z | 3,427,403 | 11 | 2010-08-06T20:11:12Z | [
"python",
"dictionary"
] | I am creating a data structure dynamically that holds car information. The dictionary looks something like this:
```
cars = {'toyota': {'prius': {'transmission':'automatic', 'mpg':30, 'misc':[]}}}
```
The outermost dictionary contains car brand (toyota, bmw, etc.), the second dictionary contains model (prius, m5, etc... | As Justin suggested, classes would be ideal.
You could easily do something like this:
```
class Car(object):
def __init__(self, make, model=None, trans=None, mpg=None, misc=None):
if make == 'Toyta' and model is None:
model = 'Prius'
self.make = make
self.model = model
... |
Compiling a regex inside a function that's called multiple times | 3,427,329 | 11 | 2010-08-06T20:00:42Z | 3,428,310 | 10 | 2010-08-06T22:42:53Z | [
"python",
"regex"
] | If you compile a regex inside a function, and that function gets called multiple times, does Python recompile the regex each time, or does Python cache the compiled regex (assuming the regex doesn't change)?
For example:
```
def contains_text_of_interest(line):
r = re.compile(r"foo\dbar\d")
return r.match(l... | Actually, if you look at the code in the re module, the re.compile function uses the cache just as all the other functions do, so compiling the same regex over and over again is very very cheap (a dictionary lookup). In other words, write the code to be the most understandable or maintainable or expressive, and don't w... |
How does Pythonic garbage collection with numpy array appends and deletes? | 3,427,632 | 4 | 2010-08-06T20:40:06Z | 3,427,728 | 8 | 2010-08-06T20:52:15Z | [
"python",
"arrays",
"memory-management",
"garbage-collection",
"numpy"
] | I am trying to adapt the underlying structure of plotting code (matplotlib) that is updated on a timer to go from using Python lists for the plot data to using numpy arrays. I want to be able to lower the time step for the plot as much as possible, and since the data may get up into the thousands of points, I start to ... | The point of automatic memory management is that you don't think about it. In the code that you wrote, the copies will be garbage-collected fine (it's nigh on impossible to confuse Python's memory management). However, because `np.append` is not in-place, the code will create a new array in memory (containing the conca... |
are there tutorials on how to name variables? | 3,427,795 | 4 | 2010-08-06T21:05:54Z | 3,427,832 | 11 | 2010-08-06T21:11:50Z | [
".net",
"python",
"language-agnostic",
"naming-conventions"
] | as you can probably tell from my previous posts i have horrific naming conventions. do you know of any tutorials dealing with how to name stuff? | i will recommend to check this book 
[http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=sr\_1\_1?s=books&ie=UTF8&qid=1281129036&sr=1-1](http:... |
are there tutorials on how to name variables? | 3,427,795 | 4 | 2010-08-06T21:05:54Z | 3,427,891 | 7 | 2010-08-06T21:20:54Z | [
".net",
"python",
"language-agnostic",
"naming-conventions"
] | as you can probably tell from my previous posts i have horrific naming conventions. do you know of any tutorials dealing with how to name stuff? | I don't think there will be any good tutorials, because there aren't any hard-and-fast rules. Here are some tips:
* Conform to convention: Loop variables are `i`, `j`, and `k`; variable numbers of arguments go in `*args` and `**kwargs`; use camelCase or underscored\_names.
* Be consistent.
* Be concise. `list_of_drugs... |
What does the unary operator ~ do in numpy? | 3,428,014 | 7 | 2010-08-06T21:43:54Z | 3,428,049 | 13 | 2010-08-06T21:49:06Z | [
"python",
"numpy"
] | I came across a line of code using Python's numpy that looked like this:
```
~array([0,1,2,3,4,5,4,3,2,1,0,-1,-2])
```
And it gave the output:
```
array([-1, -2, -3, -4, -5, -6, -5, -4, -3, -2, -1, 0, 1])
```
Does the unary operator (~) take an array and apply A -> -(A+1)
If so, whats the point? | Chris Lutz' comment is correct.
~ is the [bitwise negation operator](http://docs.python.org/library/operator.html#operator.inv)
It looks like it turns A to -(A+1) because on many modern computers, negative numbers are represented as the [Two's Complement](http://en.wikipedia.org/wiki/Two%27s_complement) of the corres... |
How to import a csv file using python with headers intact, where first column is a non-numerical | 3,428,532 | 21 | 2010-08-06T23:41:08Z | 3,428,562 | 72 | 2010-08-06T23:49:54Z | [
"python",
"csv"
] | This is an elaboration of a previous question, but as I delve deeper into python, I just get more confused as to how python handles csv files.
I have a csv file, and it must stay that way (e.g., cannot convert it to text file). It is the equivalent of a 5 rows by 11 columns array or matrix, or vector.
I have been att... | ```
import csv
with open( <path-to-file>, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
```
Python has a powerful built-in CSV handler. In fact, most th... |
How to import a csv file using python with headers intact, where first column is a non-numerical | 3,428,532 | 21 | 2010-08-06T23:41:08Z | 3,428,633 | 41 | 2010-08-07T00:15:58Z | [
"python",
"csv"
] | This is an elaboration of a previous question, but as I delve deeper into python, I just get more confused as to how python handles csv files.
I have a csv file, and it must stay that way (e.g., cannot convert it to text file). It is the equivalent of a 5 rows by 11 columns array or matrix, or vector.
I have been att... | Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.
Assuming your file is named `myclone.csv` and contains
```
workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0
```
this code should ... |
Python list subtraction operation | 3,428,536 | 85 | 2010-08-06T23:43:12Z | 3,428,547 | 103 | 2010-08-06T23:45:34Z | [
"python",
"list"
] | I want to do something similar to this:
```
>>> x = [1,2,3,4,5,6,7,8,9,0]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> y = [1,3,5,7,9]
>>> y
[1, 3, 5, 7, 9]
>>> y - x # (should return [2,4,6,8,0])
```
But this is not supported by python lists
What is the best way of doing it? | Use [set difference](http://docs.python.org/library/stdtypes.html#set.difference)
```
>>> z = list(set(x) - set(y))
>>> z
[0, 8, 2, 4, 6]
```
Or you might just have x and y be sets so you don't have to do any conversions. |
Python list subtraction operation | 3,428,536 | 85 | 2010-08-06T23:43:12Z | 3,428,550 | 17 | 2010-08-06T23:46:20Z | [
"python",
"list"
] | I want to do something similar to this:
```
>>> x = [1,2,3,4,5,6,7,8,9,0]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> y = [1,3,5,7,9]
>>> y
[1, 3, 5, 7, 9]
>>> y - x # (should return [2,4,6,8,0])
```
But this is not supported by python lists
What is the best way of doing it? | That is a "set subtraction" operation. Use the set data structure for that.
In Python 2.7:
```
x = {1,2,3,4,5,6,7,8,9,0}
y = {1,3,5,7,9}
print x - y
```
Output:
```
>>> print x - y
set([0, 8, 2, 4, 6])
``` |
Python list subtraction operation | 3,428,536 | 85 | 2010-08-06T23:43:12Z | 3,428,637 | 120 | 2010-08-07T00:19:07Z | [
"python",
"list"
] | I want to do something similar to this:
```
>>> x = [1,2,3,4,5,6,7,8,9,0]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> y = [1,3,5,7,9]
>>> y
[1, 3, 5, 7, 9]
>>> y - x # (should return [2,4,6,8,0])
```
But this is not supported by python lists
What is the best way of doing it? | Use a list comprehension:
```
[item for item in x if item not in y]
```
If you want to use the `-` infix syntax, you can just do:
```
class MyList(list):
def __init__(self, *args):
super(MyList, self).__init__(args)
def __sub__(self, other):
return self.__class__(*[item for item in self if i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.