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 to check a list contained by another list without a loop?
2,582,911
6
2010-04-06T05:52:49Z
2,582,917
22
2010-04-06T05:54:32Z
[ "python", "list" ]
As the title mentions,is there any builtins to do this job?I looked for that in `dir(list)` but got no usable one.Thanks.
Depends on what you mean by "contained". Maybe this: ``` if set(a) <= set(b): print "a is in b" ```
How to check a list contained by another list without a loop?
2,582,911
6
2010-04-06T05:52:49Z
2,582,919
8
2010-04-06T05:54:47Z
[ "python", "list" ]
As the title mentions,is there any builtins to do this job?I looked for that in `dir(list)` but got no usable one.Thanks.
Assuming that you want to see if all elements of `sublist` are also elements of `superlist`: `all(x in superlist for x in sublist)`
Dynamically create class attributes
2,583,620
7
2010-04-06T08:49:58Z
2,584,050
12
2010-04-06T10:16:43Z
[ "python", "class-attributes" ]
I need to dynamically create class attributes from a DEFAULTS dictionary. ``` defaults = { 'default_value1':True, 'default_value2':True, 'default_value3':True, } class Settings(object): default_value1 = some_complex_init_function(defaults[default_value1], ...) default_value2 = some_complex_init_fu...
You could do it without metaclasses using decorators. This way is a bit more clear IMO: ``` def apply_defaults(cls): defaults = { 'default_value1':True, 'default_value2':True, 'default_value3':True, } for name, value in defaults.items(): setattr(cls, name, some_complex_init_...
Get Django form field from model field
2,584,141
11
2010-04-06T10:36:28Z
2,584,972
10
2010-04-06T13:08:24Z
[ "python", "django", "django-models", "django-forms" ]
I'd like to create a form that includes fields from two separate models, along with some other regular (non-model) fields. The form will create an instance of each model. I don't *think* I can use inline formsets for this, since I don't want to include all the fields from both models. I'd like to create the form field...
You also can take a look to django.forms.models.fields\_for\_model That should give you a dictionary of fields, and then you can add the fields of the form
Get Django form field from model field
2,584,141
11
2010-04-06T10:36:28Z
2,587,581
8
2010-04-06T19:16:07Z
[ "python", "django", "django-models", "django-forms" ]
I'd like to create a form that includes fields from two separate models, along with some other regular (non-model) fields. The form will create an instance of each model. I don't *think* I can use inline formsets for this, since I don't want to include all the fields from both models. I'd like to create the form field...
You should never have to build the fields yourself unless you want some special behavior. This should be as simple as using two `ModelForm`s and an extra `Form` inside one `<form>` tag in your template with one submit button. in forms.py: ``` class Model1Form(forms.ModelForm): class Meta: model = Model1 ...
Python Windows File Copy with Wildcard Support
2,584,414
9
2010-04-06T11:29:34Z
2,584,474
10
2010-04-06T11:39:25Z
[ "python", "file", "wildcard", "pywin32" ]
I've been doing this all the time: ``` result = subprocess.call(['copy', '123*.xml', 'out_folder\\.', '/y']) if result == 0: do_something() else: do_something_else() ``` Until today I started to look into pywin32 modules, then I saw functions like win32file.CopyFiles(), but then I found it may not support co...
The following code provides a portable implementation. Note that I'm using iglob (added in Python 2.5) which creates a generator, so it does not load the entire list of files in memory first (which is what glob does). ``` from glob import iglob from shutil import copy from os.path import join def copy_files(src_glob...
Python Windows File Copy with Wildcard Support
2,584,414
9
2010-04-06T11:29:34Z
2,584,528
7
2010-04-06T11:47:30Z
[ "python", "file", "wildcard", "pywin32" ]
I've been doing this all the time: ``` result = subprocess.call(['copy', '123*.xml', 'out_folder\\.', '/y']) if result == 0: do_something() else: do_something_else() ``` Until today I started to look into pywin32 modules, then I saw functions like win32file.CopyFiles(), but then I found it may not support co...
The below example is fairly naive - doesn't do any checking if something goes wrong, and doesn't create any directories, but might do what you want: ``` import glob import shutil for path in glob.iglob('123*.xml'): shutil.copy(path, 'out_folder/%s' % path) ``` See also: <http://timgolden.me.uk/python/win32_how_d...
strip tags python
2,584,885
8
2010-04-06T12:52:27Z
2,585,065
9
2010-04-06T13:21:29Z
[ "python" ]
i want the following functionality. ``` input : this is test <b> bold text </b> normal text expected output: this is test normal text ``` i.e. remove the content of the specified tag
Solution using `BeautifulSoup`: ``` from BeautifulSoup import BeautifulSoup def removeTag(soup, tagname): for tag in soup.findAll(tagname): contents = tag.contents parent = tag.parent tag.extract() s = BeautifulSoup("abcd <b> btag </b> hello <d>dtag</d>") removeTag(s,"b") print s removeTa...
Emacs bulk indent for Python
2,585,091
88
2010-04-06T13:24:47Z
2,585,268
8
2010-04-06T13:47:58Z
[ "python", "emacs", "ssh" ]
Working with Python in Emacs if I want to add a try/except to a block of code, I often find that I am having to indent the whole block, line by line. In Emacs, how do you indent the whole block at once. I am not an experienced Emacs user, but just find it is the best tool for working through ssh. I am using Emacs on t...
In addition to `indent-region`, which is mapped to `C-M-\` by default, the rectangle edit commands are very useful for Python. Mark a region as normal, then: * `C-x r t` (`string-rectangle`): will prompt you for characters you'd like to insert into each line; great for inserting a certain number of spaces * `C-x r k` ...
Emacs bulk indent for Python
2,585,091
88
2010-04-06T13:24:47Z
2,585,406
134
2010-04-06T14:08:32Z
[ "python", "emacs", "ssh" ]
Working with Python in Emacs if I want to add a try/except to a block of code, I often find that I am having to indent the whole block, line by line. In Emacs, how do you indent the whole block at once. I am not an experienced Emacs user, but just find it is the best tool for working through ssh. I am using Emacs on t...
If you are programming Python using Emacs, then you should probably be using python-mode. With python-mode, after marking the block of code, `C-c >` or `C-c C-l` shifts the region 4 spaces to the right `C-c <` or `C-c C-r` shifts the region 4 spaces to the left If you need to shift code by two levels of indention, o...
Sending custom PyQt signals?
2,585,442
23
2010-04-06T14:14:20Z
2,586,512
7
2010-04-06T16:27:20Z
[ "python", "pyqt", "pyqt4", "qthread" ]
I'm practicing PyQt and (Q)threads by making a simple Twitter client. I have two Qthreads. 1. Main/GUI thread. 2. Twitter fetch thread - fetches data from Twitter every X minutes. So, every X minutes my Twitter thread downloads a new set of status updates (a Python list). I want to hand this list over to the Main/GUI...
Check out this [question I asked](http://stackoverflow.com/questions/569650/how-to-keep-track-of-thread-progress-in-python-without-freezing-the-pyqt-gui) a while back. There is a code example that might help you figure out what you need to do. What you said about registering your signal makes me think of this code (fr...
Sending custom PyQt signals?
2,585,442
23
2010-04-06T14:14:20Z
2,595,607
23
2010-04-07T20:15:58Z
[ "python", "pyqt", "pyqt4", "qthread" ]
I'm practicing PyQt and (Q)threads by making a simple Twitter client. I have two Qthreads. 1. Main/GUI thread. 2. Twitter fetch thread - fetches data from Twitter every X minutes. So, every X minutes my Twitter thread downloads a new set of status updates (a Python list). I want to hand this list over to the Main/GUI...
You can also do this, which is much more pythonic (and readable!). ``` # create a signal equivalent to "void someSignal(int, QWidget)" someSignal = QtCore.pyqtSignal(int, QtGui.QWidget) # define a slot with the same signature @QtCore.pyqtSlot(int, QtGui.QWidget) def someSlot(status, source): pass # connect the s...
Good way to edit the previous defined class in ipython
2,586,218
14
2010-04-06T15:48:52Z
2,586,580
9
2010-04-06T16:40:16Z
[ "python", "ipython" ]
I am wondering a good way to follow if i would like to redefine the members of a previous defined class in ipython. say : I have defined a class intro like below, and later i want to redefine part of the function definition \_print\_api. Any way to do that without retyping it . ``` class intro(object): def _print_a...
Use the %edit command, or its alias %ed. Assuming that the intro class already exists in the ipython namespace, typing `%ed intro` will open an external editor on the source code for the class. When you save and exit the editor the code will be executed by ipython, effectively redefining the class. The downside of thi...
Is there an easy way to "append()" two dictionaries together in Python?
2,586,273
2
2010-04-06T15:57:59Z
2,586,288
11
2010-04-06T16:00:13Z
[ "python", "dictionary" ]
If I have two dictionaries I'd like to combine in Python, i.e. ``` a = {'1': 1, '2': 2} b = {'3': 3, '4': 4} ``` If I run update on them it reorders the list: ``` a.update(b) {'1': 1, '3': 3, '2': 2, '4': 4} ``` when what I really want is attach "b" to the end of "a": ``` {'1': 1, '2': 2, '3': 3, '4': 4} ``` Is t...
A python dictionary has no ordering -- if in practice items appear in a particular order, that's purely a side-effect of the particular implementation and shouldn't be relied on.
What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
2,586,749
6
2010-04-06T17:05:13Z
2,589,031
10
2010-04-06T23:25:53Z
[ "python", "optimization" ]
I'm writing a scientific application in Python with a very processor-intensive loop at its core. I would like to optimise this as far as possible, at minimum inconvenience to end users, who will probably use it as an uncompiled collection of Python scripts, and will be using Windows, Mac, and (mainly Ubuntu) Linux. It...
You can get this to run much, much faster if you eliminate the loop and use Numpy's vectorized operations. Put your data in numpy arrays of shape (3,N) and try the following: ``` import numpy as np N = 20000 mu = np.random.random((3,1)) r_i = np.random.random((3,N)) mom_i = np.random.random((3,N)) def unit_vectors(r...
Exit to command line in Python
2,587,083
2
2010-04-06T17:51:29Z
2,587,114
7
2010-04-06T17:56:59Z
[ "python", "command-line", "scripting", "exit", "execfile" ]
I have a script that I want to exit early under some condition: ``` if not "id" in dir(): print "id not set, cannot continue" # exit here! # otherwise continue with the rest of the script... print "alright..." [ more code ] ``` I run this script using `execfile("foo.py")` from the Python interactive prompt ...
In the interactive interpreter; catch `SystemExit` raised by `sys.exit` and ignore it: ``` try: execfile("mymodule.py") except SystemExit: pass ```
Serialize the @property methods in a Python class
2,587,119
15
2010-04-06T17:57:45Z
2,607,242
11
2010-04-09T12:14:10Z
[ "python", "django", "serialization" ]
Is there a way to have any @property definitions passed through to a json serializer when serializing a Django model class? example: ``` class FooBar(object.Model) name = models.CharField(...) @property def foo(self): return "My name is %s" %self.name ``` Want to serialize to: ``` [{ 'nam...
You can extend Django's serializers without /too/ much work. Here's a custom serializer that takes a queryset and a list of attributes (fields or not), and returns JSON. ``` from StringIO import StringIO from django.core.serializers.json import Serializer class MySerializer(Serializer): def serialize(self, querys...
Python: Picking an element without replacement
2,587,387
6
2010-04-06T18:42:21Z
2,587,414
15
2010-04-06T18:46:13Z
[ "python" ]
I would like to slice random letters from a string. Given s="howdy" I would like to pick elements from 's' without replacement but keep the index number. For example ``` >>> random.sample(s,len(s)) ['w', 'h', 'o', 'd', 'y'] ``` is close to what I want, but I would actually prefer something like [('w',2), ('h',0),...
``` >>> random.sample(list(enumerate(a)), 5) [(1, 'o'), (0, 'h'), (3, 'd'), (2, 'w'), (4, 'y')] ```
Python: Picking an element without replacement
2,587,387
6
2010-04-06T18:42:21Z
2,587,415
7
2010-04-06T18:46:20Z
[ "python" ]
I would like to slice random letters from a string. Given s="howdy" I would like to pick elements from 's' without replacement but keep the index number. For example ``` >>> random.sample(s,len(s)) ['w', 'h', 'o', 'd', 'y'] ``` is close to what I want, but I would actually prefer something like [('w',2), ('h',0),...
You could just enumerate the list before sampling: ``` >>> random.sample(list(enumerate(l)), 5) [(1, 'o'), (2, 'w'), (0, 'h'), (3, 'd'), (4, 'y')] ```
Sorting Python list based on the length of the string
2,587,402
40
2010-04-06T18:45:00Z
2,587,419
83
2010-04-06T18:47:43Z
[ "python", "list", "sorting" ]
I want to sort a list of strings based on the string length. I tried to use sort as follows, but it doesn't seem to give me correct result. ``` xs = ['dddd','a','bb','ccc'] print xs xs.sort(lambda x,y: len(x) < len(y)) print xs ['dddd', 'a', 'bb', 'ccc'] ['dddd', 'a', 'bb', 'ccc'] ``` What might be wrong?
When you pass a `lambda` to `sort`, you need to return an integer, not a boolean. So your code should instead read as follows: ``` xs.sort(lambda x,y: cmp(len(x), len(y))) ``` Note that [cmp](http://docs.python.org/library/functions.html#cmp) is a builtin function such that `cmp(x, y)` returns -1 if `x` is less than ...
Sorting Python list based on the length of the string
2,587,402
40
2010-04-06T18:45:00Z
2,587,513
43
2010-04-06T19:03:29Z
[ "python", "list", "sorting" ]
I want to sort a list of strings based on the string length. I tried to use sort as follows, but it doesn't seem to give me correct result. ``` xs = ['dddd','a','bb','ccc'] print xs xs.sort(lambda x,y: len(x) < len(y)) print xs ['dddd', 'a', 'bb', 'ccc'] ['dddd', 'a', 'bb', 'ccc'] ``` What might be wrong?
The same as in Eli's answer - just using a shorter form, because you can skip a `lambda` part here. Creating new list: ``` >>> xs = ['dddd','a','bb','ccc'] >>> sorted(xs, key=len) ['a', 'bb', 'ccc', 'dddd'] ``` In-place sorting: ``` >>> xs.sort(key=len) >>> xs ['a', 'bb', 'ccc', 'dddd'] ```
Working with bytes and binary data in Python
2,587,438
3
2010-04-06T18:51:00Z
2,587,469
8
2010-04-06T18:55:55Z
[ "python", "binary", "byte" ]
Four consecutive bytes in a byte string together specify some value. However, only 7 bits in each byte are used; the most significant bit is always zero and therefore its ignored (that makes 28 bits altogether). So... ``` b"\x00\x00\x02\x01" ``` would be `000 0000` `000 0000` `000 0010` `000 0001`. Or, for the sake ...
Use bitshifting and addition: ``` bytes = b"\x00\x00\x02\x01" i = 0 for b in bytes: i <<= 7 i += b # Or use (b & 0x7f) if the last bit might not be zero. print(i) ``` Result: ``` 257 ```
Python Ephem / Datetime calculation
2,587,640
3
2010-04-06T19:23:36Z
2,587,794
7
2010-04-06T19:49:14Z
[ "python", "datetime", "astronomy" ]
the output should process the first date as "day" and second as "night". I've been playing with this for a few hours now and can't figure out what I'm doing wrong. Any ideas? **Edit** I assume that the problem is due to my date comparison implementation **Output:** ``` $ python time_of_day.py * should be day: event ...
o.date will always be between o.previous\_settings and o.next\_rising ;), so you can check it this way: ``` if o.previous_rising(ephem.Sun()) > o.previous_setting(ephem.Sun()): return "day" elif: return "night" ```
Automatically execute commands on launching python shell
2,587,709
7
2010-04-06T19:36:09Z
2,587,733
12
2010-04-06T19:39:01Z
[ "python", "shell" ]
I was wondering if there is a way to automatically run commands on entering the python shell as you would with the .bash\_profile or .profile scripts with bash. I would like to automatically import some modules so I don't have to type the whole shebang everytime I hop into the shell. Thanks,
Yup you can use the `PYTHONSTARTUP` environment variable to do this as outlined [here](http://docs.python.org/tutorial/interpreter.html#the-interactive-startup-file)
Passing a non-iterable to list.extend ()
2,588,312
3
2010-04-06T21:03:12Z
2,588,362
8
2010-04-06T21:10:03Z
[ "python", "list" ]
I am creating a public method to allow callers to write values to a device, call it write\_vals() for example. Since these values will be typed live, I would like to simplify the user's life by allowing them type in either a list or a single value, depending on how many values they need to write. For example: ``` wri...
You can check if the passed parameter is a list with the [`isinstance()`](http://docs.python.org/library/functions.html?highlight=isinstance#isinstance) function. An even better solution could be to support a variable number of arguments: ``` def write_to_device(*args): # |args| is now a list of all the arguments ...
What is the purpose of subclassing the class "object" in Python?
2,588,628
35
2010-04-06T21:54:50Z
2,588,667
41
2010-04-06T22:01:39Z
[ "python", "object", "deprecated", "future-proof", "new-style-class" ]
All the Python built-ins are subclasses of `object` and I come across many user-defined classes which are too. Why? What is the purpose of the class `object`? It's just an empty class, right?
In short, it sets free magical ponies. In long, Python 2.2 and earlier used "old style classes". They were a particular implementation of classes, and they had a few limitations (for example, you couldn't subclass builtin types). The fix for this was to create a new style of class. But, doing this would involve some b...
How can I remove all words that end in ":" from a string in Python?
2,589,200
6
2010-04-07T00:13:59Z
2,589,213
10
2010-04-07T00:18:16Z
[ "python", "regex" ]
I'm wondering how to remove a dynamic word from a string within Python. It will always have a ":" at the end of the word, and sometimes there's more than one within the string. I'd like to remove all occurrences of "word:". Thanks! :-)
Use regular expressions. ``` import re blah = "word word: monty py: thon" answer = re.sub(r'\w+:\s?','',blah) print answer ``` This will also pull out a single optional space after the colon.
Command-line input causes SyntaxError
2,589,309
3
2010-04-07T00:43:37Z
2,589,340
7
2010-04-07T00:49:53Z
[ "python", "input", "command-line", "python-2.x" ]
I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below: ``` # Compare phone number phone_pattern = '^\d{3} ?\d{3}-\d{4}$' # phoneNumber = str(input("Please enter a phone number: ")) if re.sea...
You should use `raw_input` instead of `input`, and you don't have to call `str`, because this function returns a string itself: ``` phoneNumber = raw_input("Please enter a phone number: ") ```
How do I sort this list in Python, if my date is in a String?
2,589,479
7
2010-04-07T01:36:28Z
2,589,484
19
2010-04-07T01:38:50Z
[ "python", "list", "dictionary" ]
``` [{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] ``` Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...
``` .sort(key=lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d')) ```
How do I sort this list in Python, if my date is in a String?
2,589,479
7
2010-04-07T01:36:28Z
2,589,499
18
2010-04-07T01:41:41Z
[ "python", "list", "dictionary" ]
``` [{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] ``` Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...
Fortunately, ISO format dates, which seems to be what you have here, sort perfectly well *as strings*! So you need nothing fancy: ``` import operator yourlistofdicts.sort(key=operator.itemgetter('date')) ```
How do I sort this list in Python, if my date is in a String?
2,589,479
7
2010-04-07T01:36:28Z
2,589,662
9
2010-04-07T02:37:17Z
[ "python", "list", "dictionary" ]
``` [{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] ``` Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...
Satoru.Logic's solution is clean and simple. But, per Alex's post, you don't need to manipulate the date string to get the sort order right...so lose the `.split('-')` This code will suffice: ``` records.sort(key=lambda x:x['date']) ```
Proper way to assert type of variable in Python
2,589,522
30
2010-04-07T01:51:10Z
2,589,534
7
2010-04-07T01:53:30Z
[ "python", "testing", "assert" ]
In using a function, I wish to ensure that the type of the variables are as expected. How to do it right? Here is an example fake function trying to do just this before going on with its role: ``` def my_print(begin, text, end): """Print 'text' in UPPER between 'begin' and 'end' in lower """ for i in (be...
You might want to try this example for version 2.6 of Python. ``` def my_print(text, begin, end): "Print text in UPPER between 'begin' and 'end' in lower." for obj in (text, begin, end): assert isinstance(obj, str), 'Argument of wrong type!' print begin.lower() + begin.upper() + end.lower() ``` Ho...
Proper way to assert type of variable in Python
2,589,522
30
2010-04-07T01:51:10Z
2,589,572
31
2010-04-07T02:07:32Z
[ "python", "testing", "assert" ]
In using a function, I wish to ensure that the type of the variables are as expected. How to do it right? Here is an example fake function trying to do just this before going on with its role: ``` def my_print(begin, text, end): """Print 'text' in UPPER between 'begin' and 'end' in lower """ for i in (be...
The [`isinstance`](http://docs.python.org/library/functions.html#isinstance) built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.: ``` def my_print(text, begin,...
Creating a method that is simultaneously an instance and class method
2,589,690
13
2010-04-07T02:45:09Z
2,589,706
7
2010-04-07T02:49:00Z
[ "python", "methods" ]
In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example: ``` >>> class Thing(object): #... >>> Thing.to_json() 'A' >>> Thing().to_j...
Sure, you just need to define your own **descriptor** type. There's an excellent tutorial on Python descriptors [here](http://users.rcn.com/python/download/Descriptor.htm).
Find full path of the Python interpreter?
2,589,711
144
2010-04-07T02:50:25Z
2,589,722
216
2010-04-07T02:54:34Z
[ "python", "path" ]
How do I find the full path of the currently running Python interpreter from within the currently executing Python script?
`sys.executable` contains full path of the currently running Python interpreter. ``` import sys print(sys.executable) ``` which is now [documented here](http://docs.python.org/library/sys.html)
Histogram in Matplotlib with input file
2,590,328
5
2010-04-07T06:05:17Z
2,590,548
9
2010-04-07T07:00:08Z
[ "python", "matplotlib", "histogram" ]
I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ? I am not asking for the code, some inputs should put me on the right way !
i would recommend using '**loadtxt**' which is actually in the NumPy library. There are related functions in Matplotlib (csv2rec) but Matplotlib is actually standardizing on loadtxt. Here's how it works: ``` from matplotlib import pyplot as PLT with open('name_of_your_file.csv') as f: v = NP.loadtxt(f, delimiter="...
MySQLdb not INSERTING, _mysql does fine
2,590,480
4
2010-04-07T06:41:23Z
2,590,563
17
2010-04-07T07:03:36Z
[ "python", "mysql" ]
Okay, I log onto the MySQL command-line client as root. I then open or otherwise run a python app using the MySQLdb module as root. When I check the results using python (IDLE), everything looks fine. When I use the MySQL command-line client, no INSERT has occurred. If I change things around to \_mysql instead of MySQL...
You can use `db.commit()` to submit data or set `db.autocommit()` after `_mysql.connect(...)` to autocommit requests.
how to find whether a string is contained in another string
2,590,503
2
2010-04-07T06:48:26Z
2,590,519
9
2010-04-07T06:51:34Z
[ "python", "string" ]
``` a='1234;5' print a.index('s') ``` the error is : ``` > "D:\Python25\pythonw.exe" "D:\zjm_code\kml\a.py" Traceback (most recent call last): File "D:\zjm_code\kml\a.py", line 4, in <module> print a.index('s') ValueError: substring not found ``` thanks
Try using `find()` instead - this will tell you where it is in the string: ``` a = '1234;5' index = a.find('s') if index == -1: print "Not found." else: print "Found at index", index ``` If you just want to know *whether* the string is in there, you can use `in`: ``` >>> print 's' in a False >>> print 's' no...
Find next lower item in a sorted list
2,591,159
8
2010-04-07T09:10:33Z
2,591,181
10
2010-04-07T09:14:14Z
[ "python" ]
let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n). My O(n) approach: ``` index=0 for i,value in enumerate(mylist): if val...
You can do a binary search on an array/list to get the index of the object you're looking for and get the index below it to get the lower entry (given that there actually is a lower entry!). See: <http://stackoverflow.com/questions/212358/binary-search-in-python> Be careful when [comparing floating point numbers](htt...
Find next lower item in a sorted list
2,591,159
8
2010-04-07T09:10:33Z
2,591,322
12
2010-04-07T09:36:30Z
[ "python" ]
let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n). My O(n) approach: ``` index=0 for i,value in enumerate(mylist): if val...
How about [bisect](http://docs.python.org/library/bisect.html)? ``` >>> import bisect >>> float_list = [1.0, 1.3, 2.3, 4.5] >>> i = bisect.bisect_left(float_list, 2.5) >>> index = i - 1 >>> index 2 ``` You might have to handle the case of a search value less than or equal to the lowest / leftmost value in the list se...
Getting a specific bit value in a byte string
2,591,483
4
2010-04-07T10:06:30Z
2,591,555
18
2010-04-07T10:17:59Z
[ "python", "binary", "byte" ]
There is a byte at a specific index in a byte string which represents eight flags; one flag per bit in the byte. If a flag is set, its corresponding bit is 1, otherwise its 0. For example, if I've got ``` b'\x21' ``` the flags would be ``` 0001 0101 # Three flags are set at indexes 0, 2 and 4 # and t...
Typically, the least-significant bit is bit index 0 and the most-significant bit is bit index 7. Using this terminology, we can determine if bit index k is set by taking the bitwise-and with 1 shifted to the left by k. If the bitwise and is non-zero, then that means that index k has a 1; otherwise, index k has a 0. So:...
Deploying Django (fastcgi, apache mod_wsgi, uwsgi, gunicorn)
2,591,715
15
2010-04-07T10:46:42Z
2,591,927
10
2010-04-07T11:22:10Z
[ "python", "django", "deployment", "fastcgi", "mod-wsgi" ]
Can someone explain the difference between apache mod\_wsgi in daemon mode and django fastcgi in threaded mode. They both use threads for concurrency I think. **Supposing that I'm using nginx as front end to apache mod\_wsgi.** **UPDATE:** I'm comparing django built in fastcgi(./manage.py method=threaded maxchildren=...
Neither have to use threads to be able to handle concurrent requests. It depends on how you configure them. You can use multiple processes where each is single threaded if you want. For more background on mod\_wsgi process/threading models see: <http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading> The models...
Comparing a time delta in python
2,591,845
32
2010-04-07T11:07:49Z
2,591,864
47
2010-04-07T11:10:20Z
[ "python", "datetime", "timedelta" ]
I have a variable which is `<type 'datetime.timedelta'>` and I would like to compare it against certain values. Lets say d produces this `datetime.timedelta` value `0:00:01.782000` I would like to compare it like this: ``` #if d is greater than 1 minute if d>1:00: print "elapsed time is greater than 1 minute" ```...
You'll have to [create a new `timedelta`](http://docs.python.org/library/datetime.html#datetime.timedelta) with the specified amount of time: ``` d > timedelta(minutes=1) ``` Or this slightly more complete script will help elaborate: ``` import datetime from time import sleep start = datetime.datetime.now() sleep(3...
Comparing a time delta in python
2,591,845
32
2010-04-07T11:07:49Z
2,591,875
9
2010-04-07T11:12:16Z
[ "python", "datetime", "timedelta" ]
I have a variable which is `<type 'datetime.timedelta'>` and I would like to compare it against certain values. Lets say d produces this `datetime.timedelta` value `0:00:01.782000` I would like to compare it like this: ``` #if d is greater than 1 minute if d>1:00: print "elapsed time is greater than 1 minute" ```...
You just need to create `timedelta` object from scratch, comparison after that is trivial: ``` >>> a = datetime.timedelta(minutes=1) >>> b = datetime.timedelta(minutes=1, seconds=1) >>> a < b True >>> a > b False ```
PyPy -- How can it possibly beat CPython?
2,591,879
187
2010-04-07T11:13:02Z
2,591,909
21
2010-04-07T11:17:56Z
[ "python", "pypy", "language-implementation" ]
From the [Google Open Source Blog](http://google-opensource.blogspot.com/2010/04/pypy-12-released.html): > PyPy is a reimplementation of Python > in Python, using advanced techniques > to try to attain better performance > than CPython. Many years of hard work > have finally paid off. Our speed > results often beat CP...
PyPy is implemented in Python, but it implements a JIT compiler to generate native code on the fly. The reason to implement PyPy on top of Python is probably that it is simply a very productive language, especially since the JIT compiler makes the host language's performance somewhat irrelevant.
PyPy -- How can it possibly beat CPython?
2,591,879
187
2010-04-07T11:13:02Z
2,592,094
122
2010-04-07T11:48:51Z
[ "python", "pypy", "language-implementation" ]
From the [Google Open Source Blog](http://google-opensource.blogspot.com/2010/04/pypy-12-released.html): > PyPy is a reimplementation of Python > in Python, using advanced techniques > to try to attain better performance > than CPython. Many years of hard work > have finally paid off. Our speed > results often beat CP...
**Q1. How is this possible?** Manual memory management (which is what CPython does with its counting) can be slower than automatic management in some cases. Limitations in the implementation of the CPython interpreter preclude certain optimisations that PyPy can do (eg. fine grained locks). As Marcelo mentioned, the...
PyPy -- How can it possibly beat CPython?
2,591,879
187
2010-04-07T11:13:02Z
4,221,966
11
2010-11-19T03:58:23Z
[ "python", "pypy", "language-implementation" ]
From the [Google Open Source Blog](http://google-opensource.blogspot.com/2010/04/pypy-12-released.html): > PyPy is a reimplementation of Python > in Python, using advanced techniques > to try to attain better performance > than CPython. Many years of hard work > have finally paid off. Our speed > results often beat CP...
PyPy is written in Restricted Python. It does not run on top of the CPython interpreter, as far as I know. Restricted Python is a subset of the Python language. AFAIK, the PyPy interpreter is compiled to machine code, so when installed it does not utilize a python interpreter at runtime. Your question seems to expect ...
PyPy -- How can it possibly beat CPython?
2,591,879
187
2010-04-07T11:13:02Z
8,797,731
221
2012-01-10T02:07:14Z
[ "python", "pypy", "language-implementation" ]
From the [Google Open Source Blog](http://google-opensource.blogspot.com/2010/04/pypy-12-released.html): > PyPy is a reimplementation of Python > in Python, using advanced techniques > to try to attain better performance > than CPython. Many years of hard work > have finally paid off. Our speed > results often beat CP...
"PyPy is a reimplementation of Python in Python" is a rather misleading way to describe PyPy, IMHO, although it's technically true. There are two major parts of PyPy. 1. The translation framework 2. The interpreter The translation framework is a compiler. It compiles **RPython** code down to C (or other targets), au...
What does a b prefix before a python string mean?
2,592,764
43
2010-04-07T13:28:36Z
2,592,818
35
2010-04-07T13:34:28Z
[ "python", "syntax", "python-3.x", "byte" ]
In a python source code I stumbled upon I've seen a small **b** before a string like in: ``` b"abcdef" ``` I know about the **`u`** prefix signifying a unicode string, and the **`r`** prefix for a raw string literal. What does the `b` stand for and in which kind of source code is it useful as it seems to be exactly ...
This is Python3 `bytes` [literal](http://docs.python.org/py3k/reference/lexical_analysis.html#literals). This prefix is absent in Python 2.5 and older (it is equivalent to a plain string of 2.x, while plain string of 3.x is equivalent to a literal with `u` prefix in 2.x). In Python 2.6+ it is equivalent to a plain stri...
What does a b prefix before a python string mean?
2,592,764
43
2010-04-07T13:28:36Z
24,099,252
17
2014-06-07T16:25:37Z
[ "python", "syntax", "python-3.x", "byte" ]
In a python source code I stumbled upon I've seen a small **b** before a string like in: ``` b"abcdef" ``` I know about the **`u`** prefix signifying a unicode string, and the **`r`** prefix for a raw string literal. What does the `b` stand for and in which kind of source code is it useful as it seems to be exactly ...
The `b` prefix signifies a [`bytes` string literal](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals). If you see it used in Python 3 source code, the expression creates a [`bytes` object](https://docs.python.org/3/library/stdtypes.html#bytes), not a regular [Unicode `str` object](ht...
How can I skip the current item and the next in a Python loop?
2,592,798
12
2010-04-07T13:31:53Z
2,592,879
22
2010-04-07T13:42:52Z
[ "python" ]
This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer. Is there a simple way to do something like this? ``` lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice line.next().next() ...
Try: ``` lines = iter(open('something.txt', 'r')) for val in lines: if val == "!": lines.next() continue <etc> ``` You may want to catch `StopIteration` somewhere. It'll occur if the iterator is finished.
How can I skip the current item and the next in a Python loop?
2,592,798
12
2010-04-07T13:31:53Z
2,593,100
7
2010-04-07T14:06:55Z
[ "python" ]
This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer. Is there a simple way to do something like this? ``` lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice line.next().next() ...
This is short, pythonic, and works: ``` with open('something.txt', 'r') as f: # or simply f = open('something.txt', 'r') nobang = (line for line in f if line != '!\n') for line in nobang: #... ``` Edit: As many observed, this is not the solution yet. The best I can think of is a combination of what i...
How to write a shell in Python
2,594,560
19
2010-04-07T17:31:13Z
2,594,589
18
2010-04-07T17:35:47Z
[ "python", "shell" ]
I've written a small console application that can perform certain tasks. The user interface is similar to things like version control systems or yum etc. So basically you can think of it as a domain specific language. Now I'd like to write a (bash like) shell that can execute and auto-complete this language and has a c...
You should check out the [cmd](http://docs.python.org/library/cmd.html) and [cmd2](https://bitbucket.org/catherinedevlin/cmd2) modules. I think they will do what you want. There was a PyCon [talk](http://pyvideo.org/video/306/pycon-2010--easy-command-line-applications-with-c) about these.
Removing non-breaking spaces from strings using Python
2,594,810
18
2010-04-07T18:13:25Z
2,594,942
25
2010-04-07T18:32:48Z
[ "python", "string", "unicode", "text" ]
I am having some trouble with a very basic string issue in Python (that I can't figure out). Basically, I am trying to do the following: ``` '# read file into a string myString = file.read() '# Attempt to remove non breaking spaces myString = myString.replace("\u00A0"," ") '# however, when I print my string to ou...
You don't have a unicode string, but a UTF-8 list of bytes (which are what strings are in Python 2.x). Try ``` myString = myString.replace("\xc2\xa0", " ") ``` Better would be two switch to unicode -- see [this article](http://boodebr.org/main/python/all-about-python-and-unicode#UNITEXT_IN_PYTHON) for ideas. Thus yo...
Python glob and bracket characters ('[]')
2,595,119
8
2010-04-07T19:00:10Z
2,595,162
10
2010-04-07T19:08:06Z
[ "python", "glob" ]
/Users/smcho/Desktop/bracket/[10,20] directory has "abc.txt", but when I run this Python code ``` import glob import os.path path1 = "/Users/smcho/Desktop/bracket/\[10,20\]" pathName = os.path.join(path1, "*.txt") print glob.glob(pathName) ``` It returns an empty list. * Can't Python's glob handle the bracket lette...
The brackets in `glob` are used for character classes (e.g. `[a-z]` will match lowercase letters). You can put each bracket in a character class to force them being matched: ``` path1 = "/Users/smcho/Desktop/bracket/[[]10,20[]]" ``` `[[]` is a character class containing only the character `[`, and `[]]` is a characte...
Python's Popen cleanup
2,595,602
7
2010-04-07T20:14:59Z
2,603,306
8
2010-04-08T20:41:33Z
[ "python", "popen", "resource-cleanup" ]
I wanted to use a python equivalent to piping some shell commands in perl. Something like the python version of open(PIPE, "command |"). I go to the subprocess module and try this: ``` p = subprocess.Popen("zgrep thingiwant largefile", shell=True, stdout=subprocess.PIPE) ``` This works for reading the output the sam...
The issue is that the `pipe` is full. The subprocess stops, waiting for the pipe to empty out, but then your process (the Python interpreter) quits, breaking its end of the pipe (hence the error message). `p.wait()` will not help you: > **Warning** This will deadlock if the child process generates enough output to a ...
Why does Python print unicode characters when the default encoding is ASCII?
2,596,714
113
2010-04-08T00:03:08Z
2,596,727
7
2010-04-08T00:07:43Z
[ "python", "unicode", "encoding", "ascii", "python-2.x" ]
From the Python 2.6 shell: ``` >>> import sys >>> print sys.getdefaultencoding() ascii >>> print u'\xe9' é >>> ``` I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't specified an encoding. I guess I don't understand what ASCII be...
The Python REPL tries to pick up what encoding to use from your environment. If it finds something sane then it all Just Works. It's when it can't figure out what's going on that it bugs out. ``` >>> print sys.stdout.encoding UTF-8 ```
Why does Python print unicode characters when the default encoding is ASCII?
2,596,714
113
2010-04-08T00:03:08Z
2,597,260
19
2010-04-08T02:47:04Z
[ "python", "unicode", "encoding", "ascii", "python-2.x" ]
From the Python 2.6 shell: ``` >>> import sys >>> print sys.getdefaultencoding() ascii >>> print u'\xe9' é >>> ``` I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't specified an encoding. I guess I don't understand what ASCII be...
When Unicode characters are printed to stdout, `sys.stdout.encoding` is used. A non-Unicode character is assumed to be in `sys.stdout.encoding` and is just sent to the terminal. On my system: ``` >>> import unicodedata as ud >>> import sys >>> sys.stdout.encoding 'cp437' >>> ud.name(u'\xe9') 'LATIN SMALL LETTER E WITH...
Why does Python print unicode characters when the default encoding is ASCII?
2,596,714
113
2010-04-08T00:03:08Z
21,968,640
62
2014-02-23T13:09:38Z
[ "python", "unicode", "encoding", "ascii", "python-2.x" ]
From the Python 2.6 shell: ``` >>> import sys >>> print sys.getdefaultencoding() ascii >>> print u'\xe9' é >>> ``` I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't specified an encoding. I guess I don't understand what ASCII be...
Thanks to bits and pieces from various replies, I think we can stitch up an explanation. By trying to print an unicode string, u'\xe9', Python implicitly try to encode that string using the encoding scheme currently stored in sys.stdout.encoding. Python actually picks up this setting from the environment it's been ini...
Regex to split on successions of newline characters
2,596,771
8
2010-04-08T00:20:56Z
2,597,365
18
2010-04-08T03:19:33Z
[ "python", "regex", "python-3.x" ]
I'm trying to split a string on newline characters (catering for Windows, OS X, and Unix text file newline characters). If there are any succession of these, I want to split on that too and not include *any* in the result. So, for when splitting the following: ``` "Foo\r\n\r\nDouble Windows\r\rDouble OS X\n\nDouble U...
If there are no spaces at the starts or ends of the lines, you can use `line.split()` with no arguments. It will remove doubles. . If not, you can use `[a for a a.split("\r\n") if a]`. EDIT: the `str` type also has a method called "splitlines". `"Foo\r\n\r\nDouble Windows\r\rDouble OS X\n\nDouble Unix\r\nWindows\rOS ...
Break the nested (double) loop in Python
2,597,104
26
2010-04-08T02:06:55Z
2,597,351
25
2010-04-08T03:13:41Z
[ "python", "nested-loops" ]
I use the following method to break the double loop in Python. ``` for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break ``` Is there a better way to break the double loop?
Probably not what you are hoping for, but usually you would want to have a `break` after setting `find` to `True` ``` for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True break ...
Break the nested (double) loop in Python
2,597,104
26
2010-04-08T02:06:55Z
2,597,355
7
2010-04-08T03:15:15Z
[ "python", "nested-loops" ]
I use the following method to break the double loop in Python. ``` for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break ``` Is there a better way to break the double loop?
Most times you can use a number of methods to make a single loop that does the same thing as a double loop. In your example, you can use [itertools.product](http://docs.python.org/library/itertools.html#itertools.product) to replace your code snippet with ``` import itertools for word1, word2 in itertools.product(buf...
Break the nested (double) loop in Python
2,597,104
26
2010-04-08T02:06:55Z
4,553,525
24
2010-12-29T11:06:31Z
[ "python", "nested-loops" ]
I use the following method to break the double loop in Python. ``` for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break ``` Is there a better way to break the double loop?
The recommended way in Python for breaking nested loops is... Exception ``` class Found(Exception): pass try: for i in range(100): for j in range(1000): for k in range(10000): if i + j + k == 777: raise Found except Found: print i, j, k ```
Sorting elements in string with Python
2,597,119
6
2010-04-08T02:11:35Z
2,597,134
18
2010-04-08T02:13:54Z
[ "python", "sorting" ]
I need to sort string, and I came up with the following function. ``` def mysort(comb_): str = [] size = len(comb_) for c in comb_: str.append(c) str.sort() return ''.join(str) ``` Is there any way to make it compact?
``` return ''.join(sorted(comb_)) ```
Make dictionary from list with python
2,597,166
19
2010-04-08T02:20:43Z
2,597,178
26
2010-04-08T02:22:29Z
[ "python", "list", "dictionary" ]
I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value. ``` x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} ``` ``` def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 key...
``` dict(x[i:i+2] for i in range(0, len(x), 2)) ```
Make dictionary from list with python
2,597,166
19
2010-04-08T02:20:43Z
2,597,182
10
2010-04-08T02:23:19Z
[ "python", "list", "dictionary" ]
I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value. ``` x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} ``` ``` def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 key...
``` dict(zip(*[iter(val_)] * 2)) ```
Make dictionary from list with python
2,597,166
19
2010-04-08T02:20:43Z
2,597,275
10
2010-04-08T02:50:04Z
[ "python", "list", "dictionary" ]
I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value. ``` x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} ``` ``` def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 key...
Here are a couple of ways for **Python3** using dict comprehensions ``` >>> x = (1,'a',2,'b',3,'c') >>> {k:v for k,v in zip(*[iter(x)]*2)} {1: 'a', 2: 'b', 3: 'c'} >>> {x[i]:x[i+1] for i in range(0,len(x),2)} {1: 'a', 2: 'b', 3: 'c'} ```
Make dictionary from list with python
2,597,166
19
2010-04-08T02:20:43Z
2,597,381
9
2010-04-08T03:23:19Z
[ "python", "list", "dictionary" ]
I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value. ``` x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} ``` ``` def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 key...
``` >>> x=(1,'a',2,'b',3,'c') >>> dict(zip(x[::2],x[1::2])) {1: 'a', 2: 'b', 3: 'c'} ```
Django: Odd mark_safe behaviour?
2,597,184
3
2010-04-08T02:24:10Z
5,119,089
7
2011-02-25T15:29:56Z
[ "python", "django" ]
I wrote this little function for writing out HTML tags: ``` def html_tag(tag, content=None, close=True, attrs={}): lst = ['<',tag] for key, val in attrs.iteritems(): lst.append(' %s="%s"' % (key, escape_html(val))) if close: if content is None: lst.append(' />') else: lst.extend(['>...
The `render` method of your widget is called by the `BoundField.__unicode__` function, which returns SafeString instead (of a subclass of `unicode`.) Many places in Django (e.g. `django.template.VariableNode.render`) will actually call `force_unicode` on the field instance itself. This will have the effect of doing `u...
Python: load variables in a dict into namespace
2,597,278
25
2010-04-08T02:50:31Z
2,597,440
50
2010-04-08T03:40:50Z
[ "python", "variables", "locals" ]
I want to use a bunch of local variables defined in a function, outside of the function. So I am passing `x=locals()` in the return value. How can I load all the variables defined in that dictionary into the namespace outside the function, so that instead of accessing the value using `x['variable']`, I could simply us...
Consider the `Bunch` alternative: ``` class Bunch(object): def __init__(self, adict): self.__dict__.update(adict) ``` so if you have a dictionary `d` and want to access (read) its values with the syntax `x.foo` instead of the clumsier `d['foo']`, just do ``` x = Bunch(d) ``` this works both inside and outside...
Python: load variables in a dict into namespace
2,597,278
25
2010-04-08T02:50:31Z
4,014,070
11
2010-10-25T11:24:40Z
[ "python", "variables", "locals" ]
I want to use a bunch of local variables defined in a function, outside of the function. So I am passing `x=locals()` in the return value. How can I load all the variables defined in that dictionary into the namespace outside the function, so that instead of accessing the value using `x['variable']`, I could simply us...
This is perfectly valid case to import variables in one local space into another local space as long as one is aware of what he/she is doing. I have seen such code many times being used in useful ways. Just need to be careful not to pollute common global space. You can do the following: ``` adict = { 'x' : 'I am x', ...
Python: load variables in a dict into namespace
2,597,278
25
2010-04-08T02:50:31Z
4,906,299
7
2011-02-05T10:20:25Z
[ "python", "variables", "locals" ]
I want to use a bunch of local variables defined in a function, outside of the function. So I am passing `x=locals()` in the return value. How can I load all the variables defined in that dictionary into the namespace outside the function, so that instead of accessing the value using `x['variable']`, I could simply us...
Importing variables into a local namespace is a valid problem and often utilized in templating frameworks. Return all local variables from a function: ``` return locals() ``` Then import as follows: ``` r = fce() for key in r.keys(): exec(key + " = r['" + key + "']") ```
random.randint(1,n) in Python
2,597,444
7
2010-04-08T03:41:31Z
2,597,446
9
2010-04-08T03:43:26Z
[ "python", "random" ]
Most of us know that the command `random.randint(1,n)` in Python (2.X.X) would generate a number in random (pseudo-random) between 1 and n. I am interested in knowing what is the upper limit for n ?
`randint()` works with long integers, so there is no upper limit: ``` >>> random.randint(1,123456789012345678901234567890) 113144971884331658209492153398L ```
Is there a way to loop through and execute all of the functions in a Python class?
2,597,827
5
2010-04-08T05:51:15Z
2,597,895
8
2010-04-08T06:06:58Z
[ "python", "reflection", "class" ]
I have ``` class Foo(): function bar(): pass function foobar(): pass ``` Rather than executing each function one by one as follows: ``` x = Foo() x.bar() x.foobar() ``` is there a built-in way to loop through and execute each function in the sequence in which they are written in the class?
``` def assignOrder(order): @decorator def do_assignment(to_func): to_func.order = order return to_func return do_assignment class Foo(): @assignOrder(1) def bar(self): print "bar" @assignOrder(2) def foo(self): print "foo" #don't decorate functions you don't want called def __init...
Generate fixed length hash in python for url parameter
2,597,833
10
2010-04-08T05:53:24Z
2,597,938
8
2010-04-08T06:16:19Z
[ "python", "google-app-engine", "url", "hash" ]
I am working in python on appengine. I am trying to create what is equivalent to the "v" value in the youtube url's (http://www.youtube.com/watch?v=**XhMN0wlITLk**) for retrieving specific entities. The datastore auto generates a key but it is way too long (34 digits). I have experimented with hashlib to build my own,...
You can use the auto generated [integer id](http://code.google.com/appengine/docs/python/datastore/keyclass.html#Key_id) of the key to generate the hash. A simple way to generate the hash would be to convert the integer id to base62 (alphanumeric). To fetch the object simply convert to decimal back from base62 and use ...
how to change [1,2,3,4] to '1234' using python
2,597,932
5
2010-04-08T06:15:01Z
2,597,937
20
2010-04-08T06:16:08Z
[ "python", "string", "list" ]
How do I convert a list of `int`s to a single string, such that: `[1, 2, 3, 4]` becomes `'1234'` `[10, 11, 12, 13]` becomes `'10111213'` ... etc...
``` ''.join(map(str, [1,2,3,4] )) ``` * [`map(str, array)`](http://docs.python.org/library/functions.html#map) is equivalent to `[str(x) for x in array]`, so `map(str, [1,2,3,4])` returns `['1', '2', '3', '4']`. * [`s.join(a)`](http://docs.python.org/library/stdtypes.html#str.join) concatenates all items in the sequen...
how to change [1,2,3,4] to '1234' using python
2,597,932
5
2010-04-08T06:15:01Z
2,597,952
12
2010-04-08T06:20:11Z
[ "python", "string", "list" ]
How do I convert a list of `int`s to a single string, such that: `[1, 2, 3, 4]` becomes `'1234'` `[10, 11, 12, 13]` becomes `'10111213'` ... etc...
``` ''.join(str(i) for i in [1,2,3,4]) ```
What does this python line mean?
2,598,069
2
2010-04-08T06:50:14Z
2,598,072
8
2010-04-08T06:51:38Z
[ "python", "syntax" ]
``` abc = [0, ] * datalen; ``` "`datalen`" is an `Integer`. Then I see referencing like this: ``` abc[-1] ``` Any ideas?
creates a list with `datalen` references to the object `0`: ``` >>> datalen = 10 >>> print [0,] * datalen [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ``` You don't really need the comma in there: ``` >>> print [0] * datalen [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ```
How to retrieve the process start time (or uptime) in python
2,598,145
22
2010-04-08T07:11:54Z
2,598,201
13
2010-04-08T07:23:35Z
[ "python", "linux", "process", "uptime" ]
How to retrieve the process start time (or uptime) in python in Linux? I only know, I can call "ps -p my\_process\_id -f" and then parse the output. But it is not cool.
If you are doing it from within the python program you're trying to measure, you could do something like this: ``` import time # at the beginning of the script startTime = time.time() # ... def getUptime(): """ Returns the number of seconds since the program started. """ # do return startTime if you ju...
How to retrieve the process start time (or uptime) in python
2,598,145
22
2010-04-08T07:11:54Z
2,598,284
12
2010-04-08T07:43:07Z
[ "python", "linux", "process", "uptime" ]
How to retrieve the process start time (or uptime) in python in Linux? I only know, I can call "ps -p my\_process\_id -f" and then parse the output. But it is not cool.
[`man proc`](http://linux.die.net/man/5/proc) says that the 22nd item in `/proc/my_process_id/stat` is: > `starttime %lu` > > The time in jiffies the process started after system boot. Your problem now is, how to determine the length of a jiffy and how to determine when the system booted. The answer for the latter c...
How to retrieve the process start time (or uptime) in python
2,598,145
22
2010-04-08T07:11:54Z
4,559,733
30
2010-12-30T03:09:26Z
[ "python", "linux", "process", "uptime" ]
How to retrieve the process start time (or uptime) in python in Linux? I only know, I can call "ps -p my\_process\_id -f" and then parse the output. But it is not cool.
By using psutil <https://github.com/giampaolo/psutil>: ``` >>> import psutil, os, time >>> p = psutil.Process(os.getpid()) >>> p.create_time() 1293678383.0799999 >>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(p.create_time())) '2010-12-30 04:06:23' >>> ``` ...plus it's cross platform, not only Linux. NB: I am...
How to Implement a Binary Tree in Python
2,598,437
39
2010-04-08T08:23:42Z
25,859,412
11
2014-09-16T01:33:49Z
[ "python", "algorithm", "search", "binary-tree" ]
Which is the best data structure that can be used to implement Binary Tree in Python?
``` # simple binary tree # in this implementation, a node is inserted between an existing node and the root class BinaryTree(): def __init__(self,rootid): self.left = None self.right = None self.rootid = rootid def getLeftChild(self): return self.left def getRightChild(self): ...
How to Implement a Binary Tree in Python
2,598,437
39
2010-04-08T08:23:42Z
28,864,021
30
2015-03-04T20:14:59Z
[ "python", "algorithm", "search", "binary-tree" ]
Which is the best data structure that can be used to implement Binary Tree in Python?
Here is my simple recursive implementation of binary tree. ``` #!/usr/bin/python class Node: def __init__(self, val): self.l = None self.r = None self.v = val class Tree: def __init__(self): self.root = None def getRoot(self): return self.root def add(self, v...
Numpy: Creating a complex array from 2 real ones?
2,598,734
28
2010-04-08T09:22:49Z
2,598,820
32
2010-04-08T09:38:22Z
[ "python", "arrays", "numpy", "complex-numbers" ]
I swear this should be so easy... Why is it not? :( In fact, I want to combine 2 parts of the same array to make a complex array: ``` Data[:,:,:,0] , Data[:,:,:,1] ``` These don't work: ``` x = np.complex(Data[:,:,:,0], Data[:,:,:,1]) x = complex(Data[:,:,:,0], Data[:,:,:,1]) ``` Am I missing something? Does numpy...
This seems to do what you want: ``` numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data) ``` Here is another solution: ``` numpy.vectorize(complex)(Data[...,0], Data[...,1]) # The ellipsis is equivalent here to ":,:,:" ``` And yet another simpler solution: ``` Data[...,0] + 1j * Data[...,1] ``` **PS**:...
Numpy: Creating a complex array from 2 real ones?
2,598,734
28
2010-04-08T09:22:49Z
12,288,514
19
2012-09-05T19:34:07Z
[ "python", "arrays", "numpy", "complex-numbers" ]
I swear this should be so easy... Why is it not? :( In fact, I want to combine 2 parts of the same array to make a complex array: ``` Data[:,:,:,0] , Data[:,:,:,1] ``` These don't work: ``` x = np.complex(Data[:,:,:,0], Data[:,:,:,1]) x = complex(Data[:,:,:,0], Data[:,:,:,1]) ``` Am I missing something? Does numpy...
There's of course the rather obvious: ``` Data[...,0] + 1j * Data[...,1] ```
Numpy: Creating a complex array from 2 real ones?
2,598,734
28
2010-04-08T09:22:49Z
20,955,309
9
2014-01-06T17:09:09Z
[ "python", "arrays", "numpy", "complex-numbers" ]
I swear this should be so easy... Why is it not? :( In fact, I want to combine 2 parts of the same array to make a complex array: ``` Data[:,:,:,0] , Data[:,:,:,1] ``` These don't work: ``` x = np.complex(Data[:,:,:,0], Data[:,:,:,1]) x = complex(Data[:,:,:,0], Data[:,:,:,1]) ``` Am I missing something? Does numpy...
This is what your are looking for: ``` from numpy import array a=array([1,2,3]) b=array([4,5,6]) a + 1j*b ->array([ 1.+4.j, 2.+5.j, 3.+6.j]) ```
Numpy: Creating a complex array from 2 real ones?
2,598,734
28
2010-04-08T09:22:49Z
21,996,376
12
2014-02-24T18:51:09Z
[ "python", "arrays", "numpy", "complex-numbers" ]
I swear this should be so easy... Why is it not? :( In fact, I want to combine 2 parts of the same array to make a complex array: ``` Data[:,:,:,0] , Data[:,:,:,1] ``` These don't work: ``` x = np.complex(Data[:,:,:,0], Data[:,:,:,1]) x = complex(Data[:,:,:,0], Data[:,:,:,1]) ``` Am I missing something? Does numpy...
If your real and imaginary parts are the slices along the last dimension and your array is contiguous along the last dimension, you can just do ``` A.view(dtype=np.complex128) ``` If you are using single precision floats, this would be ``` A.view(dtype=np.complex64) ``` Here is a fuller example ``` import numpy as...
Python recursion with list returns None
2,599,149
8
2010-04-08T10:41:09Z
2,599,169
11
2010-04-08T10:44:34Z
[ "python", "list", "recursion" ]
``` def foo(a): a.append(1) if len(a) > 10: print a return a else: foo(a) ``` Why this recursive function returns None (see transcript below)? I can't quite understand what I am doing wrong. ``` In [263]: x = [] In [264]: y = foo(x) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] In [265]: pri...
You don't return anything in the `else` clause: ``` else: return foo(a) ```
How can I count the occurrences of a list item in Python?
2,600,191
592
2010-04-08T13:30:00Z
2,600,208
816
2010-04-08T13:31:52Z
[ "python", "list", "count" ]
Given an item, how can I count its occurrences in a list in Python?
``` >>> [1, 2, 3, 4, 1, 4, 1].count(1) 3 ```
How can I count the occurrences of a list item in Python?
2,600,191
592
2010-04-08T13:30:00Z
2,600,231
30
2010-04-08T13:34:15Z
[ "python", "list", "count" ]
Given an item, how can I count its occurrences in a list in Python?
`list.count(x)` returns the number of times `x` appears in a list see: <http://docs.python.org/tutorial/datastructures.html#more-on-lists>
How can I count the occurrences of a list item in Python?
2,600,191
592
2010-04-08T13:30:00Z
5,829,377
913
2011-04-29T07:44:22Z
[ "python", "list", "count" ]
Given an item, how can I count its occurrences in a list in Python?
If you are using Python 2.7 or 3 and you want number of occurrences for each element: ``` >>> from collections import Counter >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] >>> Counter(z) Counter({'blue': 3, 'red': 2, 'yellow': 1}) ```
How can I count the occurrences of a list item in Python?
2,600,191
592
2010-04-08T13:30:00Z
7,055,873
9
2011-08-14T08:47:39Z
[ "python", "list", "count" ]
Given an item, how can I count its occurrences in a list in Python?
``` # Python >= 2.6 (defaultdict) && < 2.7 (Counter, OrderedDict) from collections import defaultdict def count_unsorted_list_items(items): """ :param items: iterable of hashable items to count :type items: iterable :returns: dict of counts like Py2.7 Counter :rtype: dict """ counts = defau...
How can I count the occurrences of a list item in Python?
2,600,191
592
2010-04-08T13:30:00Z
7,843,090
46
2011-10-20T22:38:08Z
[ "python", "list", "count" ]
Given an item, how can I count its occurrences in a list in Python?
Another way to get the number of occurrences of each item, in a dictionary: ``` dict((i, a.count(i)) for i in a) ```
How can I count the occurrences of a list item in Python?
2,600,191
592
2010-04-08T13:30:00Z
8,041,395
9
2011-11-07T19:18:54Z
[ "python", "list", "count" ]
Given an item, how can I count its occurrences in a list in Python?
I had this problem today and rolled my own solution before I thought to check SO. This: ``` dict((i,a.count(i)) for i in a) ``` is really, really slow for large lists. My solution ``` def occurDict(items): d = {} for i in items: if i in d: d[i] = d[i]+1 else: d[i] = 1 ...
How can I count the occurrences of a list item in Python?
2,600,191
592
2010-04-08T13:30:00Z
20,069,518
17
2013-11-19T10:53:07Z
[ "python", "list", "count" ]
Given an item, how can I count its occurrences in a list in Python?
If you want to **count all values at once** you can do it very fast using numpy arrays and `bincount` as follows ``` import numpy as np a = np.array([1, 2, 3, 4, 1, 4, 1]) np.bincount(a) ``` which gives ``` >>> array([0, 3, 1, 1, 2]) ```
How can I count the occurrences of a list item in Python?
2,600,191
592
2010-04-08T13:30:00Z
23,909,767
84
2014-05-28T10:58:37Z
[ "python", "list", "count" ]
Given an item, how can I count its occurrences in a list in Python?
**Counting the occurrences of one item in a list** For counting the occurrences of just one list item you can use `count()` ``` >>> l = ["a","b","b"] >>> l.count("a") 1 >>> l.count("b") 2 ``` Counting the occurrences of *all* items in a list is also known as "tallying" a list, or creating a tally counter. **Countin...
How to get week number in Python?
2,600,775
139
2010-04-08T14:35:52Z
2,600,864
180
2010-04-08T14:47:19Z
[ "python", "datetime", "week-number" ]
How to find out what week number is this year on June 16th (wk24) with Python?
`datetime.date` has a `isocalendar()` method, which returns a tuple containing the calendar week: ``` >>> datetime.date(2010, 6, 16).isocalendar()[1] 24 ``` [datetime.date.isocalendar()](http://docs.python.org/library/datetime.html#datetime.date.isocalendar) is an instance-method returning a tuple containing year, we...
How to get week number in Python?
2,600,775
139
2010-04-08T14:35:52Z
2,600,878
47
2010-04-08T14:48:58Z
[ "python", "datetime", "week-number" ]
How to find out what week number is this year on June 16th (wk24) with Python?
I believe `date.isocalendar()` is going to be the answer. [This article](http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm) explains the math behind ISO 8601 Calendar. Check out the date.isocalendar() portion of the [datetime page](http://docs.python.org/library/datetime.html#datetime.date.isocalendar) of the Pytho...
How to get week number in Python?
2,600,775
139
2010-04-08T14:35:52Z
2,600,888
16
2010-04-08T14:50:04Z
[ "python", "datetime", "week-number" ]
How to find out what week number is this year on June 16th (wk24) with Python?
Here's another option: ``` import time from time import gmtime, strftime d = time.strptime("16 Jun 2010", "%d %b %Y") print(strftime("%U", d)) ``` which prints `24`. See: <http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior>
How to get week number in Python?
2,600,775
139
2010-04-08T14:35:52Z
2,608,868
8
2010-04-09T15:52:03Z
[ "python", "datetime", "week-number" ]
How to find out what week number is this year on June 16th (wk24) with Python?
The ISO week suggested by others is a good one, but it might not fit your needs. It assumes each week begins with a Monday, which leads to some interesting anomalies at the beginning and end of the year. If you'd rather use a definition that says week 1 is always January 1 through January 7 regardless of the day of th...