title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
Can 3D OpenGL game written in Python look good and run fast?
| 641,770
|
<p>I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). </p>
<p>When I was planning what to do, I started wondering about switching to Python. I know that Python didn't come into existence to be a tool to write 3d games, but is it possible to write good looking games with this language? </p>
<p>I have in mind 3d graphics, nice effects and free CPU time to power to rest of game engine? I had seen good looking java games - and too be honest, I was rather shocked when I saw level of detail achieved in Runescape HD. </p>
<p>On the other hand, pygame.org has only 2d games, with some starting 3d projects. Are there any efficient 3d game engines for python? Is pyopengl the only alternative? Good looking games in python aren't popular or possible to achieve? </p>
<p>I would be grateful for any information / feedback.</p>
| 12
|
2009-03-13T07:48:58Z
| 641,863
|
<p>Perhaps a wee bit off topic but, if your goal is to learn Python, how about creating a game using <a href="http://www.ironpython.com/" rel="nofollow">IronPython</a> and <a href="http://www.xna.com/" rel="nofollow">XNA</a>? XNA is not OpenGL though, yet I find it an extremely simple 2D/3D engine which is fast and supports Shader Model 3.0.</p>
| 1
|
2009-03-13T08:54:43Z
|
[
"python",
"opengl"
] |
Can 3D OpenGL game written in Python look good and run fast?
| 641,770
|
<p>I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). </p>
<p>When I was planning what to do, I started wondering about switching to Python. I know that Python didn't come into existence to be a tool to write 3d games, but is it possible to write good looking games with this language? </p>
<p>I have in mind 3d graphics, nice effects and free CPU time to power to rest of game engine? I had seen good looking java games - and too be honest, I was rather shocked when I saw level of detail achieved in Runescape HD. </p>
<p>On the other hand, pygame.org has only 2d games, with some starting 3d projects. Are there any efficient 3d game engines for python? Is pyopengl the only alternative? Good looking games in python aren't popular or possible to achieve? </p>
<p>I would be grateful for any information / feedback.</p>
| 12
|
2009-03-13T07:48:58Z
| 641,907
|
<p>Check out the <a href="http://fretsonfire.sourceforge.net/screenshots/" rel="nofollow">Frets on Fire</a> project -- an open source Guitar Hero alternative. It's written in Python and has decent 3D graphics in OpenGL. I would suggest checking out <a href="http://fretsonfire.sourceforge.net/documentation/source/" rel="nofollow">its sources</a> for hints on libraries etc.</p>
| 1
|
2009-03-13T09:15:55Z
|
[
"python",
"opengl"
] |
Can 3D OpenGL game written in Python look good and run fast?
| 641,770
|
<p>I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). </p>
<p>When I was planning what to do, I started wondering about switching to Python. I know that Python didn't come into existence to be a tool to write 3d games, but is it possible to write good looking games with this language? </p>
<p>I have in mind 3d graphics, nice effects and free CPU time to power to rest of game engine? I had seen good looking java games - and too be honest, I was rather shocked when I saw level of detail achieved in Runescape HD. </p>
<p>On the other hand, pygame.org has only 2d games, with some starting 3d projects. Are there any efficient 3d game engines for python? Is pyopengl the only alternative? Good looking games in python aren't popular or possible to achieve? </p>
<p>I would be grateful for any information / feedback.</p>
| 12
|
2009-03-13T07:48:58Z
| 642,096
|
<p>Yes. Eve Online does it.</p>
<p><a href="http://support.eve-online.com/Pages/KB/Article.aspx?id=128">http://support.eve-online.com/Pages/KB/Article.aspx?id=128</a></p>
| 8
|
2009-03-13T10:25:30Z
|
[
"python",
"opengl"
] |
Can 3D OpenGL game written in Python look good and run fast?
| 641,770
|
<p>I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). </p>
<p>When I was planning what to do, I started wondering about switching to Python. I know that Python didn't come into existence to be a tool to write 3d games, but is it possible to write good looking games with this language? </p>
<p>I have in mind 3d graphics, nice effects and free CPU time to power to rest of game engine? I had seen good looking java games - and too be honest, I was rather shocked when I saw level of detail achieved in Runescape HD. </p>
<p>On the other hand, pygame.org has only 2d games, with some starting 3d projects. Are there any efficient 3d game engines for python? Is pyopengl the only alternative? Good looking games in python aren't popular or possible to achieve? </p>
<p>I would be grateful for any information / feedback.</p>
| 12
|
2009-03-13T07:48:58Z
| 642,375
|
<p>I would recommend <a href="http://www.pyglet.org/" rel="nofollow">pyglet</a> which is a similar system to pygame, but with full bindings to OpenGL. You can start with simple 2D games to get the hang of the system and work up to 3D later. It is a more modern system than PyGame which is built around SDL which itself is a bit long in the tooth these days.</p>
| 2
|
2009-03-13T12:09:29Z
|
[
"python",
"opengl"
] |
Can 3D OpenGL game written in Python look good and run fast?
| 641,770
|
<p>I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). </p>
<p>When I was planning what to do, I started wondering about switching to Python. I know that Python didn't come into existence to be a tool to write 3d games, but is it possible to write good looking games with this language? </p>
<p>I have in mind 3d graphics, nice effects and free CPU time to power to rest of game engine? I had seen good looking java games - and too be honest, I was rather shocked when I saw level of detail achieved in Runescape HD. </p>
<p>On the other hand, pygame.org has only 2d games, with some starting 3d projects. Are there any efficient 3d game engines for python? Is pyopengl the only alternative? Good looking games in python aren't popular or possible to achieve? </p>
<p>I would be grateful for any information / feedback.</p>
| 12
|
2009-03-13T07:48:58Z
| 645,987
|
<p>There was a Vampires game out a few years ago where most if not all of the code was in Python. Not sure if the 3D routines were in them, but it worked fine.</p>
| 1
|
2009-03-14T14:29:57Z
|
[
"python",
"opengl"
] |
Can 3D OpenGL game written in Python look good and run fast?
| 641,770
|
<p>I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). </p>
<p>When I was planning what to do, I started wondering about switching to Python. I know that Python didn't come into existence to be a tool to write 3d games, but is it possible to write good looking games with this language? </p>
<p>I have in mind 3d graphics, nice effects and free CPU time to power to rest of game engine? I had seen good looking java games - and too be honest, I was rather shocked when I saw level of detail achieved in Runescape HD. </p>
<p>On the other hand, pygame.org has only 2d games, with some starting 3d projects. Are there any efficient 3d game engines for python? Is pyopengl the only alternative? Good looking games in python aren't popular or possible to achieve? </p>
<p>I would be grateful for any information / feedback.</p>
| 12
|
2009-03-13T07:48:58Z
| 11,417,357
|
<p>I did a EuroPython talk about my amateur attempts to drive OpenGL from Python:
<a href="http://pyvideo.org/video/381/pycon-2011--algorithmic-generation-of-opengl-geom" rel="nofollow">http://pyvideo.org/video/381/pycon-2011--algorithmic-generation-of-opengl-geom</a></p>
<p>The latest version of the code I'm talking about is here:
<a href="https://github.com/tartley/gloopy" rel="nofollow">https://github.com/tartley/gloopy</a></p>
<p>It's billed as a 'library', but that was naive of me: It's a bunch of personal experimental code.</p>
<p>Nevertheless, it demonstrates that you can move around hundreds of bits of geometry at 60fps from Python.</p>
<p>Although the demo above is fairly bare-bones in that it uses simply geometry and untextured faces, one thing I found is that more detailed geometry, texture mapping or other more modern graphics effects don't substantially affect the framerate. Or at least they don't affect it any worse than using the same effects in a C program. These are run on the GPU, so it doesn't make any difference at all if your program is written in Python.</p>
<p>One thing that is performance-sensitive from Python is if you are creating dynamic geometry on the CPU side, e.g. moving individual vertices within a shape, by bending or melting the shape. Doing this sort of per-vertex calculation in Python, then constructing a new ctypes array from the result, then shunting this geometry to the GPU, every frame, will be slow. Instead you should probably be doing this in a vertex shader.</p>
<p>On the other hand, if you just want affine transformations (moving objects around, rotating them, opening chests of drawers, rotating car wheels, bending a jointed robot arm) then all of this can be done by the GPU and the fact your program is written in Python makes little difference to the performance.</p>
| 3
|
2012-07-10T16:03:30Z
|
[
"python",
"opengl"
] |
Highlighting trailing whitespace in Textmate for Python?
| 641,794
|
<p>I would like to do something like <a href="http://remysharp.com/2008/03/30/trailing-white-space-in-textmate/">this</a> Textmate tip, so that trailing whitespace are always highlighted in some way when I code something in Python - it makes it easier to correct it immediately and other editors such as Emacs can do it.</p>
<p>Unfortunately the discussion after that post seems to suggest it's difficult to do. For me the <code>invalid.trailing-whitespace</code> scope selector is not even visible in the preferences after following this tip. Has anyone else had any success with this?</p>
| 11
|
2009-03-13T08:02:43Z
| 645,160
|
<p>I don't know how to highlight the trailing space but you can remove it by going to</p>
<p>Bundles -> Text -> Converting/Stripping -> Remove trailing spaces in document</p>
<p>Also, because textmate has emacs bindings, you may be able to do it the same way you would do it in emacs.</p>
| 5
|
2009-03-14T01:45:21Z
|
[
"python",
"osx",
"textmate"
] |
Highlighting trailing whitespace in Textmate for Python?
| 641,794
|
<p>I would like to do something like <a href="http://remysharp.com/2008/03/30/trailing-white-space-in-textmate/">this</a> Textmate tip, so that trailing whitespace are always highlighted in some way when I code something in Python - it makes it easier to correct it immediately and other editors such as Emacs can do it.</p>
<p>Unfortunately the discussion after that post seems to suggest it's difficult to do. For me the <code>invalid.trailing-whitespace</code> scope selector is not even visible in the preferences after following this tip. Has anyone else had any success with this?</p>
| 11
|
2009-03-13T08:02:43Z
| 670,341
|
<p>This code works (but not with comment) :</p>
<pre><code>{ scopeName = 'source.whitespace';
patterns = (
{ name = 'source.invalid.trailing-whitespace';
match = '(\s+)$';
captures = { 1 = { name = 'invalid.trailing-whitespace'; }; };
},
);
}
</code></pre>
<p>PS: I have changed "source" to "source.whitespace"</p>
<p>For comment change in Python grammar :</p>
<pre><code>{ name = 'comment.line.number-sign.python';
match = '(#).*$\n?';
captures = { 1 = { name = 'punctuation.definition.comment.python'; }; };
},
</code></pre>
<p>In:</p>
<pre><code>{ name = 'comment.line.number-sign.python';
match = '(#).*?(\s*)$\n?';
captures = {
1 = { name = 'punctuation.definition.comment.python'; };
2 = { name = 'invalid.trailing-whitespace'; };
};
},
</code></pre>
<p>You'll need to add an 'include' in Python language definition where:</p>
<pre><code>:
patterns = (
{ name = 'comment.line.number-sign.python';
:
</code></pre>
<p>Turns to:</p>
<pre><code>:
patterns = (
{ include = 'source.whitespace'; },
{ name = 'comment.line.number-sign.python';
:
</code></pre>
| 5
|
2009-03-22T00:44:01Z
|
[
"python",
"osx",
"textmate"
] |
Rename files, Python/Jython
| 641,985
|
<p>I have a directory full of files, some which have an ampersand in their names. I would like to rename all the files with ampersands and replace each ampersand with a plus (+). I am working with around 10k files. What would be the best method to do this?</p>
| 5
|
2009-03-13T09:48:05Z
| 642,004
|
<pre><code>import glob, os
for filename in glob.glob(os.path.join(yourPath, "*&*")):
os.rename(filename, filename.replace('&','+'))
</code></pre>
| 13
|
2009-03-13T09:58:43Z
|
[
"python",
"file",
"jython",
"rename"
] |
Rename files, Python/Jython
| 641,985
|
<p>I have a directory full of files, some which have an ampersand in their names. I would like to rename all the files with ampersands and replace each ampersand with a plus (+). I am working with around 10k files. What would be the best method to do this?</p>
| 5
|
2009-03-13T09:48:05Z
| 642,087
|
<pre><code>import os
directory = '.'
for file in os.listdir(directory):
if '&' in file :
os.rename(file, file.replace('&', '+'))
</code></pre>
<p>Replace <code>directory</code> with your own path.</p>
| 2
|
2009-03-13T10:23:09Z
|
[
"python",
"file",
"jython",
"rename"
] |
Rename files, Python/Jython
| 641,985
|
<p>I have a directory full of files, some which have an ampersand in their names. I would like to rename all the files with ampersands and replace each ampersand with a plus (+). I am working with around 10k files. What would be the best method to do this?</p>
| 5
|
2009-03-13T09:48:05Z
| 642,295
|
<p>If you have subdirectories:</p>
<pre><code>import os
for dirpath, dirs, files in os.walk(your_path):
for filename in files:
if '&' in filename:
os.rename(
os.path.join(dirpath, filename),
os.path.join(dirpath, filename.replace('&', '+'))
)
</code></pre>
| 7
|
2009-03-13T11:42:25Z
|
[
"python",
"file",
"jython",
"rename"
] |
Rename files, Python/Jython
| 641,985
|
<p>I have a directory full of files, some which have an ampersand in their names. I would like to rename all the files with ampersands and replace each ampersand with a plus (+). I am working with around 10k files. What would be the best method to do this?</p>
| 5
|
2009-03-13T09:48:05Z
| 18,965,017
|
<p>using <a href="https://github.com/75lb/rename" rel="nofollow">rename</a>:</p>
<pre><code>$ rename --find '&' --replace '+' *
</code></pre>
| 0
|
2013-09-23T17:10:00Z
|
[
"python",
"file",
"jython",
"rename"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 642,169
|
<p><a href="https://docs.python.org/2/library/functions.html#int"><code>int()</code></a> is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an actual integer:</p>
<pre><code>print int("1") + 1
</code></pre>
<p>The above prints <code>2</code>.</p>
<p>If you know the structure of your list (that it simply contains lists, only one level), you could do this:</p>
<pre><code>T2 = [map(int, x) for x in T1]
</code></pre>
| 322
|
2009-03-13T10:58:42Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 642,177
|
<p>You can do this with a list comprehension:</p>
<pre><code>T2 = [[int(column) for column in row] for row in T1]
</code></pre>
<p>The inner list comprehension (<code>[int(column) for column in row]</code>) builds a <code>list</code> of <code>int</code>s from a sequence of <code>int</code>-able objects, like decimal strings, in <code>row</code>. The outer list comprehension (<code>[... for row in T1])</code>) builds a list of the results of the inner list comprehension applied to each item in <code>T1</code>.</p>
<p>The code snippet will fail if any of the rows contain objects that can't be converted by <code>int</code>. You'll need a smarter function if you want to process rows containing non-decimal strings.</p>
<p>If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.</p>
<pre><code>T2 = [parse_a_row_of_T1(row) for row in T1]
</code></pre>
| 21
|
2009-03-13T11:02:30Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 642,185
|
<p>If it's only a tuple of tuples, something like <code>rows=[map(int, row) for row in rows]</code> will do the trick. (There's a list comprehension and a call to map(f, lst), which is equal to [f(a) for a in lst], in there.)</p>
<p>Eval is <em>not</em> what you want to do, in case there's something like <code>__import__("os").unlink("importantsystemfile")</code> in your database for some reason.
Always validate your input (if with nothing else, the exception int() will raise if you have bad input).</p>
| 0
|
2009-03-13T11:04:40Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 642,189
|
<p>Using list comprehensions:</p>
<pre><code>t2 = [map(int, list(l)) for l in t1]
</code></pre>
| 3
|
2009-03-13T11:06:14Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 642,872
|
<p>I would agree with everyones answers so far but the problem is is that if you do not have all integers they will crash.</p>
<p>If you wanted to exclude non-integers then</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
new_list = list(list(int(a) for a in b) for b in T1 if a.isdigit())
</code></pre>
<p>This yields only actual digits. The reason I don't use direct list comprehensions is because list comprehension leaks their internal variables.</p>
| 7
|
2009-03-13T14:05:10Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 855,419
|
<p>I would rather prefer using only comprehension lists:</p>
<pre><code>[[int(y) for y in x] for x in T1]
</code></pre>
| 12
|
2009-05-12T23:33:41Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 5,426,537
|
<pre><code>T3=[]
for i in range(0,len(T1)):
T3.append([])
for j in range(0,len(T1[i])):
b=int(T1[i][j])
T3[i].append(b)
print T3
</code></pre>
| 9
|
2011-03-24T22:53:40Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 21,344,009
|
<p>Instead of putting int(), put float() which will let you use decimals along with integers</p>
| 6
|
2014-01-24T22:56:32Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 30,549,317
|
<p>Try this.</p>
<pre><code>x = "1"
</code></pre>
<p>x is a string because it has quotes around it, but it has a number in it.</p>
<pre><code>x = int(x)
</code></pre>
<p>Since x has the number 1 in it, I can turn it in to a integer.</p>
<p>To see if a string is a number, you can do this.</p>
<pre><code>def is_number(var):
try:
if var == int(var):
return True
except Exception:
return False
x = "1"
y = "test"
x_test = is_number(x)
print(x_test)
</code></pre>
<p>It should print to IDLE True because x is a number.</p>
<pre><code>y_test = is_number(y)
print(y_test)
</code></pre>
<p>It should print to IDLE False because y in not a number.</p>
| 4
|
2015-05-30T17:38:14Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 31,148,598
|
<p>Wont work for everything but....</p>
<pre><code>T2 = eval(str(T1).replace("'","").replace("(","[").replace(")","]"))
</code></pre>
<p>in your case it would fail because numbers with leading 0's will be read as octal or break. But if your numeric notations doesn't have that it works well.</p>
| -2
|
2015-06-30T21:12:17Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 37,489,104
|
<p>In Python 3.5.1 things like these work:</p>
<pre><code>c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))
</code></pre>
<p>and</p>
<pre><code>Enter number: 4.7
4
5
</code></pre>
<p>George.</p>
| 0
|
2016-05-27T17:17:22Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 37,956,572
|
<pre><code>for str in T2 :
return num(str)
</code></pre>
<p>maybe that;ll work</p>
| -3
|
2016-06-22T00:11:06Z
|
[
"python",
"string",
"integer"
] |
How to convert strings into integers in Python?
| 642,154
|
<p>I have a tuple of tuples from a MySQL query like this:</p>
<pre><code>T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
</code></pre>
<p>I'd like to convert all the string elements into integers and put it back nicely to list of lists this time:</p>
<pre><code>T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>I tried to achieve it with <code>eval</code> but didn't get any decent result yet.</p>
| 211
|
2009-03-13T10:53:59Z
| 38,778,859
|
<p>Yet another functional solution for Python 2:</p>
<pre><code>from functools import partial
map(partial(map, int), T1)
</code></pre>
<p>Python 3 will be a little bit messy though:</p>
<pre><code>list(map(list, map(partial(map, int), T1)))
</code></pre>
| 0
|
2016-08-04T23:22:12Z
|
[
"python",
"string",
"integer"
] |
How do I format positional argument help using Python's optparse?
| 642,648
|
<p>As mentioned in <a href="http://docs.python.org/library/optparse.html?highlight=indentedhelpformatter#creating-the-parser">the docs</a> the <code>optparse.OptionParser</code> uses an <code>IndentedHelpFormatter</code> to output the formatted option help, for which which I found some <a href="http://corebio.googlecode.com/svn/tags/0.5.0/apidocs/optparse.IndentedHelpFormatter-class.html">API documentation</a>.</p>
<p><strong>I want to display a similarly formatted help text for the required, positional arguments</strong> in the usage text. Is there an adapter or a simple usage pattern that can be used for similar positional argument formatting?</p>
<h3>Clarification</h3>
<p>Preferably only using the stdlib. Optparse does great except for this one formatting nuance, which I feel like we should be able to fix without importing whole other packages. :-)</p>
| 22
|
2009-03-13T13:16:56Z
| 642,717
|
<p>Most help text for positional arguments resembles the format frequently used in man pages for *NIX boxes. Take a look at <a href="http://www.linuxmanpages.com/man1/cp.1.php" rel="nofollow">how the 'cp' command is documented</a>. Your help text should resemble that. </p>
<p>Otherwise as long as you fill out the "help" argument while using the parser, the documentation should produce itself.</p>
| 0
|
2009-03-13T13:32:27Z
|
[
"python",
"command-line",
"formatting",
"command-line-arguments",
"optparse"
] |
How do I format positional argument help using Python's optparse?
| 642,648
|
<p>As mentioned in <a href="http://docs.python.org/library/optparse.html?highlight=indentedhelpformatter#creating-the-parser">the docs</a> the <code>optparse.OptionParser</code> uses an <code>IndentedHelpFormatter</code> to output the formatted option help, for which which I found some <a href="http://corebio.googlecode.com/svn/tags/0.5.0/apidocs/optparse.IndentedHelpFormatter-class.html">API documentation</a>.</p>
<p><strong>I want to display a similarly formatted help text for the required, positional arguments</strong> in the usage text. Is there an adapter or a simple usage pattern that can be used for similar positional argument formatting?</p>
<h3>Clarification</h3>
<p>Preferably only using the stdlib. Optparse does great except for this one formatting nuance, which I feel like we should be able to fix without importing whole other packages. :-)</p>
| 22
|
2009-03-13T13:16:56Z
| 642,782
|
<p>I'd be interested in a clean solution to this; I wasn't able to come up with one. The OptionParser really focuses entirely on the options; it doesn't give you anything to work with position args, as far as I've been able to find.</p>
<p>What I did was to generate a list of little documentation blocks for each of my positional arguments, using <code>\t</code>s to get the right spacing. Then I joined them with newlines, and appended that to the 'usage' string that gets passed to the OptionParser.</p>
<p>It looks fine, but it feels silly, and of course that documentation ends up appearing above the list of options. I haven't found any way around that, or how to do any complex stuff, i.e. a given set of options is described beneath the description for a positional arg, because they only apply to that arg.</p>
<p>I looked at monkey-patching OptionParser's methods and I remember (this was a year or so ago) that it wouldn't have been that difficult, but I didn't want to go down that path.</p>
| 1
|
2009-03-13T13:46:09Z
|
[
"python",
"command-line",
"formatting",
"command-line-arguments",
"optparse"
] |
How do I format positional argument help using Python's optparse?
| 642,648
|
<p>As mentioned in <a href="http://docs.python.org/library/optparse.html?highlight=indentedhelpformatter#creating-the-parser">the docs</a> the <code>optparse.OptionParser</code> uses an <code>IndentedHelpFormatter</code> to output the formatted option help, for which which I found some <a href="http://corebio.googlecode.com/svn/tags/0.5.0/apidocs/optparse.IndentedHelpFormatter-class.html">API documentation</a>.</p>
<p><strong>I want to display a similarly formatted help text for the required, positional arguments</strong> in the usage text. Is there an adapter or a simple usage pattern that can be used for similar positional argument formatting?</p>
<h3>Clarification</h3>
<p>Preferably only using the stdlib. Optparse does great except for this one formatting nuance, which I feel like we should be able to fix without importing whole other packages. :-)</p>
| 22
|
2009-03-13T13:16:56Z
| 643,797
|
<p>Try taking a look at <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">argparse</a>. Documentation says it supports position arguments and nicer looking help messages.</p>
| 8
|
2009-03-13T17:34:22Z
|
[
"python",
"command-line",
"formatting",
"command-line-arguments",
"optparse"
] |
How do I format positional argument help using Python's optparse?
| 642,648
|
<p>As mentioned in <a href="http://docs.python.org/library/optparse.html?highlight=indentedhelpformatter#creating-the-parser">the docs</a> the <code>optparse.OptionParser</code> uses an <code>IndentedHelpFormatter</code> to output the formatted option help, for which which I found some <a href="http://corebio.googlecode.com/svn/tags/0.5.0/apidocs/optparse.IndentedHelpFormatter-class.html">API documentation</a>.</p>
<p><strong>I want to display a similarly formatted help text for the required, positional arguments</strong> in the usage text. Is there an adapter or a simple usage pattern that can be used for similar positional argument formatting?</p>
<h3>Clarification</h3>
<p>Preferably only using the stdlib. Optparse does great except for this one formatting nuance, which I feel like we should be able to fix without importing whole other packages. :-)</p>
| 22
|
2009-03-13T13:16:56Z
| 664,614
|
<p>The best bet would be to write a patch to the optparse module. In the meantime, you can accomplish this with a slightly modified OptionParser class. This isn't perfect, but it'll get what you want done.</p>
<pre><code>#!/usr/bin/env python
from optparse import OptionParser, Option, IndentedHelpFormatter
class PosOptionParser(OptionParser):
def format_help(self, formatter=None):
class Positional(object):
def __init__(self, args):
self.option_groups = []
self.option_list = args
positional = Positional(self.positional)
formatter = IndentedHelpFormatter()
formatter.store_option_strings(positional)
output = ['\n', formatter.format_heading("Positional Arguments")]
formatter.indent()
pos_help = [formatter.format_option(opt) for opt in self.positional]
pos_help = [line.replace('--','') for line in pos_help]
output += pos_help
return OptionParser.format_help(self, formatter) + ''.join(output)
def add_positional_argument(self, option):
try:
args = self.positional
except AttributeError:
args = []
args.append(option)
self.positional = args
def set_out(self, out):
self.out = out
def main():
usage = "usage: %prog [options] bar baz"
parser = PosOptionParser(usage)
parser.add_option('-f', '--foo', dest='foo',
help='Enable foo')
parser.add_positional_argument(Option('--bar', action='store_true',
help='The bar positional argument'))
parser.add_positional_argument(Option('--baz', action='store_true',
help='The baz positional argument'))
(options, args) = parser.parse_args()
if len(args) != 2:
parser.error("incorrect number of arguments")
pass
if __name__ == '__main__':
main()
</code></pre>
<p>And the output you get from running this:</p>
<pre><code>Usage: test.py [options] bar baz
Options:
-h, --help show this help message and exit
-f FOO, --foo=FOO Enable foo
Positional Arguments:
bar The bar positional argument
baz The baz positional argument
</code></pre>
| 19
|
2009-03-20T00:57:55Z
|
[
"python",
"command-line",
"formatting",
"command-line-arguments",
"optparse"
] |
Is it possible to replace a function/method decorator at runtime? [ python ]
| 642,762
|
<p>If I have a function :</p>
<pre><code>
@aDecorator
def myfunc1():
# do something here
if __name__ = "__main__":
# this will call the function and will use the decorator @aDecorator
myfunc1()
# now I want the @aDecorator to be replaced with the decorator @otherDecorator
# so that when this code executes, the function no longer goes through
# @aDecorator, but instead through @otherDecorator. How can I do this?
myfunc1()
</code></pre>
<p>Is it possible to replace a decorator at runtime?</p>
| 13
|
2009-03-13T13:42:33Z
| 642,771
|
<p>If the decorator is a function, just replace it.</p>
<pre><code>aDecorator = otherDecorator
</code></pre>
| -1
|
2009-03-13T13:43:58Z
|
[
"python",
"runtime",
"language-features",
"decorator"
] |
Is it possible to replace a function/method decorator at runtime? [ python ]
| 642,762
|
<p>If I have a function :</p>
<pre><code>
@aDecorator
def myfunc1():
# do something here
if __name__ = "__main__":
# this will call the function and will use the decorator @aDecorator
myfunc1()
# now I want the @aDecorator to be replaced with the decorator @otherDecorator
# so that when this code executes, the function no longer goes through
# @aDecorator, but instead through @otherDecorator. How can I do this?
myfunc1()
</code></pre>
<p>Is it possible to replace a decorator at runtime?</p>
| 13
|
2009-03-13T13:42:33Z
| 642,821
|
<p>If you want to explicitely change the decorator, you might as well choose a more explicit approach instead of creating a decorated function:</p>
<pre><code>deco1(myfunc1, arg1, arg2)
deco2(myfunc1, arg2, arg3)
</code></pre>
<p>deco1() and deco2() would apply the functionality your decorators provide and call myfunc1() with the arguments.</p>
| 0
|
2009-03-13T13:53:41Z
|
[
"python",
"runtime",
"language-features",
"decorator"
] |
Is it possible to replace a function/method decorator at runtime? [ python ]
| 642,762
|
<p>If I have a function :</p>
<pre><code>
@aDecorator
def myfunc1():
# do something here
if __name__ = "__main__":
# this will call the function and will use the decorator @aDecorator
myfunc1()
# now I want the @aDecorator to be replaced with the decorator @otherDecorator
# so that when this code executes, the function no longer goes through
# @aDecorator, but instead through @otherDecorator. How can I do this?
myfunc1()
</code></pre>
<p>Is it possible to replace a decorator at runtime?</p>
| 13
|
2009-03-13T13:42:33Z
| 642,832
|
<p>As Miya mentioned, you can replace the decorator with another function any point before the interpreter gets to that function declaration. However, once the decorator is applied to the function, I don't think there is a way to dynamically replace the decorator with a different one. So for example:</p>
<pre><code>@aDecorator
def myfunc1():
pass
# Oops! I didn't want that decorator after all!
myfunc1 = bDecorator(myfunc1)
</code></pre>
<p>Won't work, because myfunc1 is no longer the function you originally defined; it has already been wrapped. The best approach here is to manually apply the decorators, oldskool-style, i.e:</p>
<pre><code>def myfunc1():
pass
myfunc2 = aDecorator(myfunc1)
myfunc3 = bDecorator(myfunc1)
</code></pre>
<p>Edit: Or, to be a little clearer,</p>
<pre><code>def _tempFunc():
pass
myfunc1 = aDecorator(_tempFunc)
myfunc1()
myfunc1 = bDecorator(_tempFunc)
myfunc1()
</code></pre>
| 10
|
2009-03-13T13:55:56Z
|
[
"python",
"runtime",
"language-features",
"decorator"
] |
Is it possible to replace a function/method decorator at runtime? [ python ]
| 642,762
|
<p>If I have a function :</p>
<pre><code>
@aDecorator
def myfunc1():
# do something here
if __name__ = "__main__":
# this will call the function and will use the decorator @aDecorator
myfunc1()
# now I want the @aDecorator to be replaced with the decorator @otherDecorator
# so that when this code executes, the function no longer goes through
# @aDecorator, but instead through @otherDecorator. How can I do this?
myfunc1()
</code></pre>
<p>Is it possible to replace a decorator at runtime?</p>
| 13
|
2009-03-13T13:42:33Z
| 642,842
|
<p>Here's a terrific <a href="http://code.activestate.com/recipes/528929/" rel="nofollow">recipe to get you started</a>. Basically, the idea is to pass a class instance into the decorator. You can then set attributes on the class instance (make it a Borg if you like) and use that to control the behavior of the decorator itself.</p>
<p>Here's an example:</p>
<pre><code>class Foo:
def __init__(self, do_apply):
self.do_apply = do_apply
def dec(foo):
def wrap(f):
def func(*args, **kwargs):
if foo.do_apply:
# Do something!
pass
return f(*args, **kwargs)
return func
return wrap
foo = Foo(False)
@dec(foo)
def bar(x):
return x
bar('bar')
foo.do_apply = True
# Decorator now active!
bar('baz')
</code></pre>
<p>Naturally, you can also incorporate the "decorator decorator" to preserve signatures, etc.</p>
| 3
|
2009-03-13T13:59:40Z
|
[
"python",
"runtime",
"language-features",
"decorator"
] |
Is it possible to replace a function/method decorator at runtime? [ python ]
| 642,762
|
<p>If I have a function :</p>
<pre><code>
@aDecorator
def myfunc1():
# do something here
if __name__ = "__main__":
# this will call the function and will use the decorator @aDecorator
myfunc1()
# now I want the @aDecorator to be replaced with the decorator @otherDecorator
# so that when this code executes, the function no longer goes through
# @aDecorator, but instead through @otherDecorator. How can I do this?
myfunc1()
</code></pre>
<p>Is it possible to replace a decorator at runtime?</p>
| 13
|
2009-03-13T13:42:33Z
| 643,089
|
<p>I don't know if there's a way to "replace" a decorator once it has been applied, but I guess that probably there's not, because the function has already been changed.</p>
<p>You might, anyway, apply a decorator at runtime based on some condition:</p>
<pre><code>#!/usr/bin/env python
class PrintCallInfo:
def __init__(self,f):
self.f = f
def __call__(self,*args,**kwargs):
print "-->",self.f.__name__,args,kwargs
r = self.f(*args,**kwargs)
print "<--",self.f.__name__,"returned: ",r
return r
# the condition to modify the function...
some_condition=True
def my_decorator(f):
if (some_condition): # modify the function
return PrintCallInfo(f)
else: # leave it as it is
return f
@my_decorator
def foo():
print "foo"
@my_decorator
def bar(s):
print "hello",s
return s
@my_decorator
def foobar(x=1,y=2):
print x,y
return x + y
foo()
bar("world")
foobar(y=5)
</code></pre>
| 2
|
2009-03-13T14:55:06Z
|
[
"python",
"runtime",
"language-features",
"decorator"
] |
Is it possible to replace a function/method decorator at runtime? [ python ]
| 642,762
|
<p>If I have a function :</p>
<pre><code>
@aDecorator
def myfunc1():
# do something here
if __name__ = "__main__":
# this will call the function and will use the decorator @aDecorator
myfunc1()
# now I want the @aDecorator to be replaced with the decorator @otherDecorator
# so that when this code executes, the function no longer goes through
# @aDecorator, but instead through @otherDecorator. How can I do this?
myfunc1()
</code></pre>
<p>Is it possible to replace a decorator at runtime?</p>
| 13
|
2009-03-13T13:42:33Z
| 4,200,091
|
<p>Sure - you can get the function object and do whatever you want with it:</p>
<pre><code># Bypass a decorator
import types
class decorator_test(object):
def __init__(self, f):
self.f = f
def __call__(self):
print "In decorator ... entering: ", self.f.__name__
self.f()
print "In decorator ... exiting: ", self.f.__name__
@decorator_test
def func1():
print "inside func1()"
print "\nCalling func1 with decorator..."
func1()
print "\nBypassing decorator..."
for value in func1.__dict__.values():
if isinstance(value, types.FunctionType) and value.func_name == "func1":
value.__call__()
</code></pre>
| 1
|
2010-11-16T23:26:59Z
|
[
"python",
"runtime",
"language-features",
"decorator"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 642,774
|
<p>Do you consider <code>[1,2]</code> to intersect with <code>[1, [2]]</code>? That is, is it only the numbers you care about, or the list structure as well?</p>
<p>If only the numbers, investigate how to "flatten" the lists, then use the <code>set()</code> method.</p>
| 2
|
2009-03-13T13:45:14Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 642,790
|
<p>You should flatten using this code ( taken from <a href="http://kogs-www.informatik.uni-hamburg.de/~meine/python%5Ftricks" rel="nofollow">http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks</a> ), the code is untested, but I'm pretty sure it works:</p>
<pre><code>
def flatten(x):
"""flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
result = []
for el in x:
#if isinstance(el, (list, tuple)):
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
</code></pre>
<p>After you had flattened the list, you perform the intersection in the usual way:</p>
<pre><code>
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
def intersect(a, b):
return list(set(a) & set(b))
print intersect(flatten(c1), flatten(c2))
</code></pre>
| 4
|
2009-03-13T13:47:08Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 642,895
|
<p><strong>If you want:</strong></p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [[13, 32], [7, 13, 28], [1,6]]
</code></pre>
<p><strong>Then here is your solution for Python 2:</strong></p>
<pre><code>c3 = [filter(lambda x: x in c1, sublist) for sublist in c2]
</code></pre>
<p><strong>In Python 3 <code>filter</code> returns an iterable instead of <code>list</code>, so you need to wrap <code>filter</code> calls with <code>list()</code>:</strong></p>
<pre><code>c3 = [list(filter(lambda x: x in c1, sublist)) for sublist in c2]
</code></pre>
<p><strong>Explanation:</strong> </p>
<p>The filter part takes each sublist's item and checks to see if it is in the source list c1.
The list comprehension is executed for each sublist in c2. </p>
| 120
|
2009-03-13T14:11:13Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 642,919
|
<p>You don't need to define intersection. It's already a first-class part of set.</p>
<pre><code>>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> set(b1).intersection(b2)
set([4, 5])
</code></pre>
| 549
|
2009-03-13T14:16:46Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 642,992
|
<h3>Pure list comprehension version</h3>
<pre><code>>>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
>>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
>>> c1set = frozenset(c1)
</code></pre>
<p>Flatten variant:</p>
<pre><code>>>> [n for lst in c2 for n in lst if n in c1set]
[13, 32, 7, 13, 28, 1, 6]
</code></pre>
<p>Nested variant:</p>
<pre><code>>>> [[n for n in lst if n in c1set] for lst in c2]
[[13, 32], [7, 13, 28], [1, 6]]
</code></pre>
| 21
|
2009-03-13T14:35:58Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 1,404,146
|
<p>The functional approach:</p>
<pre><code>input_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]
result = reduce(set.intersection, map(set, input_list))
</code></pre>
<p>and it can be applied to the more general case of 1+ lists</p>
| 14
|
2009-09-10T08:50:21Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 1,875,493
|
<p>For people just looking to find the intersection of two lists, the Asker provided two methods:</p>
<blockquote>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>and</p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
</blockquote>
<p>But there is a hybrid method that is more efficient, because you only have to do one conversion between list/set, as opposed to three:</p>
<pre><code>b1 = [1,2,3,4,5]
b2 = [3,4,5,6]
s2 = set(b2)
b3 = [val for val in b1 if val in s2]
</code></pre>
<p>This will run in O(n), whereas his original method involving list comprehension will run in O(n^2)</p>
| 39
|
2009-12-09T17:26:06Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 9,376,917
|
<p>Since <code>intersect</code> was defined, a basic list comprehension is enough:</p>
<pre><code>>>> c3 = [intersect(c1, i) for i in c2]
>>> c3
[[32, 13], [28, 13, 7], [1, 6]]
</code></pre>
<p>Improvement thanks to S. Lott's remark and TM.'s associated remark:</p>
<pre><code>>>> c3 = [list(set(c1).intersection(i)) for i in c2]
>>> c3
[[32, 13], [28, 13, 7], [1, 6]]
</code></pre>
| 3
|
2012-02-21T11:38:00Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 11,278,430
|
<p>I don't know if I am late in answering your question. After reading your question I came up with a function intersect() that can work on both list and nested list. I used recursion to define this function, it is very intuitive. Hope it is what you are looking for:</p>
<pre><code>def intersect(a, b):
result=[]
for i in b:
if isinstance(i,list):
result.append(intersect(a,i))
else:
if i in a:
result.append(i)
return result
</code></pre>
<p>Example:</p>
<pre><code>>>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
>>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
>>> print intersect(c1,c2)
[[13, 32], [7, 13, 28], [1, 6]]
>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> print intersect(b1,b2)
[4, 5]
</code></pre>
| 3
|
2012-06-30T23:23:23Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 23,028,000
|
<p>Given:</p>
<blockquote>
<p>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]</p>
<p>c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]</p>
</blockquote>
<p>I find the following code works well and maybe more concise if using set operation:</p>
<blockquote>
<p>c3 = [list(set(f)&set(c1)) for f in c2] </p>
</blockquote>
<p>It got:</p>
<blockquote>
<p>[[32, 13], [28, 13, 7], [1, 6]]</p>
</blockquote>
<p>If order needed:</p>
<blockquote>
<p>c3 = [sorted(list(set(f)&set(c1))) for f in c2] </p>
</blockquote>
<p>we got:</p>
<blockquote>
<p>[[13, 32], [7, 13, 28], [1, 6]]</p>
</blockquote>
<p>By the way, for a more python style, this one is fine too:</p>
<blockquote>
<p>c3 = [ [i for i in set(f) if i in c1] for f in c2]</p>
</blockquote>
| 2
|
2014-04-12T08:21:15Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 27,057,507
|
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [list(set(c2[i]).intersection(set(c1))) for i in xrange(len(c2))]
c3
->[[32, 13], [28, 13, 7], [1, 6]]
</code></pre>
| 0
|
2014-11-21T08:59:50Z
|
[
"python",
"list",
"intersection"
] |
Python - Intersection of two lists
| 642,763
|
<p>I know how to get an intersection of two flat lists:</p>
<pre><code>b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
</code></pre>
<p>or </p>
<pre><code>def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
</code></pre>
<p>But when I have to find intersection for nested lists then my problems starts:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
</code></pre>
<p>In the end I would like to receive:</p>
<pre><code>c3 = [[13,32],[7,13,28],[1,6]]
</code></pre>
<p>Can you guys give me a hand with this?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 271
|
2009-03-13T13:42:44Z
| 30,052,495
|
<p>We can use set methods for this:</p>
<pre><code>c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
result = []
for li in c2:
res = set(li) & set(c1)
result.append(list(res))
print result
</code></pre>
| 0
|
2015-05-05T12:05:52Z
|
[
"python",
"list",
"intersection"
] |
WinXP button-style with wxPython
| 642,853
|
<p>I noticed that my programs written with wxPython have Win98 button style.
But Boa Constructor (that is written using wxPython too) got pretty buttons.</p>
<p>How to make buttons look like current Windows buttons style?</p>
| 3
|
2009-03-13T14:01:28Z
| 642,948
|
<p>Have you tried running your scripts with pythonw.exe instead of python.exe?</p>
| -2
|
2009-03-13T14:26:00Z
|
[
"python",
"coding-style",
"wxpython"
] |
WinXP button-style with wxPython
| 642,853
|
<p>I noticed that my programs written with wxPython have Win98 button style.
But Boa Constructor (that is written using wxPython too) got pretty buttons.</p>
<p>How to make buttons look like current Windows buttons style?</p>
| 3
|
2009-03-13T14:01:28Z
| 643,165
|
<p>Are you packaging the app with py2exe?</p>
<p>If so you may need to specify a manifest file to make Python use the WinXP(Vista?) theme/Common Controls:</p>
<p><a href="http://wiki.wxpython.org/DistributingYourApplication" rel="nofollow">http://wiki.wxpython.org/DistributingYourApplication</a></p>
| 3
|
2009-03-13T15:12:38Z
|
[
"python",
"coding-style",
"wxpython"
] |
WinXP button-style with wxPython
| 642,853
|
<p>I noticed that my programs written with wxPython have Win98 button style.
But Boa Constructor (that is written using wxPython too) got pretty buttons.</p>
<p>How to make buttons look like current Windows buttons style?</p>
| 3
|
2009-03-13T14:01:28Z
| 643,178
|
<p>Expanding on <a href="http://stackoverflow.com/questions/642853/winxp-button-style-with-wxpython/643165#643165">John's answer</a>, you may also be able to create manifest files for <code>python.exe</code> and <code>pythonw.exe</code> to see the new styles without first packaging using py2exe.</p>
| 1
|
2009-03-13T15:15:26Z
|
[
"python",
"coding-style",
"wxpython"
] |
WinXP button-style with wxPython
| 642,853
|
<p>I noticed that my programs written with wxPython have Win98 button style.
But Boa Constructor (that is written using wxPython too) got pretty buttons.</p>
<p>How to make buttons look like current Windows buttons style?</p>
| 3
|
2009-03-13T14:01:28Z
| 841,710
|
<p>The answers so far handle distributing the package as an executable (eg. py2exe), where the answer has already been given.</p>
<p>But since (i think) python 2.6 you have the same problem when just starting the <code>.py</code> file from the commandline (Vista and Windows7). Robin Dunn suggested using <code>update_manifest.py</code> which he distributes with wxPython and puts it in the same directory as python.exe.</p>
<p>After applying <code>update_manifest.py</code> using a copied version of python.exe wxPython apps have the correct themed look and yes it also works using windows7 RC1.</p>
| 0
|
2009-05-08T20:44:54Z
|
[
"python",
"coding-style",
"wxpython"
] |
Python script at Visual C++ 2005 build step not spawning other processes
| 642,877
|
<p>I have the following post-build step in a VC++ 2005 project that calls a Python 2.5.1 script:</p>
<pre><code>postbuild.py
</code></pre>
<p>postbuild.py does:</p>
<pre><code>import os
os.system('cd') # cd is just a test, could be anything
</code></pre>
<p>The process never starts, and it's the same with any other process I try, even using subprocess.call or Popen instead of os.system.</p>
<p>Does anyone know about anything related to problems like this in Python 2.5.1 or in build events in Visual C++ 2005 SP1?</p>
| 2
|
2009-03-13T14:06:30Z
| 642,955
|
<p>Be aware that the post build event will only run immediately after a completed build. If the project had already been built (and so does not need building again), then the post build step will not run at all.</p>
<p>If you're editing the python script and then trying to get it to run by building the project, then it's not going to do anything unless you edit a file within the project each time, to force the build to occur.</p>
| 0
|
2009-03-13T14:27:07Z
|
[
"python",
"visual-c++",
"post-build-event",
"spawn",
"spawning"
] |
Python script at Visual C++ 2005 build step not spawning other processes
| 642,877
|
<p>I have the following post-build step in a VC++ 2005 project that calls a Python 2.5.1 script:</p>
<pre><code>postbuild.py
</code></pre>
<p>postbuild.py does:</p>
<pre><code>import os
os.system('cd') # cd is just a test, could be anything
</code></pre>
<p>The process never starts, and it's the same with any other process I try, even using subprocess.call or Popen instead of os.system.</p>
<p>Does anyone know about anything related to problems like this in Python 2.5.1 or in build events in Visual C++ 2005 SP1?</p>
| 2
|
2009-03-13T14:06:30Z
| 643,005
|
<p>Solved. For some reason, using "postbuild.py" as postbuild step inhibits the python script from spawning other processes, where "python.exe postbuild.py" has no problems, and neither "pythonw.exe postbuild.py". I'm not sure why this happens, as all three methods are valid when used from cmd.exe.</p>
<p>But I would like to know if anyone has an explanation for this.</p>
| 2
|
2009-03-13T14:39:37Z
|
[
"python",
"visual-c++",
"post-build-event",
"spawn",
"spawning"
] |
regular expression help with converting exp1^exp2 to pow(exp1, exp2)
| 643,173
|
<p>I am converting some matlab code to C, currently I have some lines that have powers using the ^, which is rather easy to do with something along the lines <code>\(?(\w*)\)?\^\(?(\w*)\)?</code></p>
<p>works fine for converting <code>(glambda)^(galpha)</code>,using the sub routine in python <code>pattern.sub(pow(\g<1>,\g<2>),'(glambda)^(galpha)')</code></p>
<p>My problem comes with nested parenthesis</p>
<p>So I have a string like:</p>
<p><code>glambdastar^(1-(1-gphi)*galpha)*(glambdaq)^(-(1-gphi)*galpha);</code></p>
<p>And I can not figure out how to convert that line to:</p>
<p><code>pow(glambdastar,(1-(1-gphi)*galpha))*pow(glambdaq,-(1-gphi)*galpha));</code></p>
| 2
|
2009-03-13T15:14:07Z
| 643,200
|
<p>Nested parenthesis cannot be described by a regexp and require a full parser (able to understand a grammar, which is something more powerful than a regexp). I do not think there is a solution.</p>
| 0
|
2009-03-13T15:19:04Z
|
[
"python",
"c",
"regex"
] |
regular expression help with converting exp1^exp2 to pow(exp1, exp2)
| 643,173
|
<p>I am converting some matlab code to C, currently I have some lines that have powers using the ^, which is rather easy to do with something along the lines <code>\(?(\w*)\)?\^\(?(\w*)\)?</code></p>
<p>works fine for converting <code>(glambda)^(galpha)</code>,using the sub routine in python <code>pattern.sub(pow(\g<1>,\g<2>),'(glambda)^(galpha)')</code></p>
<p>My problem comes with nested parenthesis</p>
<p>So I have a string like:</p>
<p><code>glambdastar^(1-(1-gphi)*galpha)*(glambdaq)^(-(1-gphi)*galpha);</code></p>
<p>And I can not figure out how to convert that line to:</p>
<p><code>pow(glambdastar,(1-(1-gphi)*galpha))*pow(glambdaq,-(1-gphi)*galpha));</code></p>
| 2
|
2009-03-13T15:14:07Z
| 643,204
|
<p>Unfortunately, regular expressions aren't the right tool for handling nested structures. There are some regular expressions engines (such as .NET) which have some support for recursion, but most â including the Python engine â do not, and can only handle as many levels of nesting as you build into the expression (which gets ugly fast).</p>
<p>What you really need for this is a simple parser. For example, iterate over the string counting parentheses and storing their locations in a list. When you find a <code>^</code> character, put the most recently closed parenthesis group into a "left" variable, then watch the group formed by the next opening parenthesis. When it closes, use it as the "right" value and print the <code>pow(left, right)</code> expression.</p>
| 2
|
2009-03-13T15:21:04Z
|
[
"python",
"c",
"regex"
] |
regular expression help with converting exp1^exp2 to pow(exp1, exp2)
| 643,173
|
<p>I am converting some matlab code to C, currently I have some lines that have powers using the ^, which is rather easy to do with something along the lines <code>\(?(\w*)\)?\^\(?(\w*)\)?</code></p>
<p>works fine for converting <code>(glambda)^(galpha)</code>,using the sub routine in python <code>pattern.sub(pow(\g<1>,\g<2>),'(glambda)^(galpha)')</code></p>
<p>My problem comes with nested parenthesis</p>
<p>So I have a string like:</p>
<p><code>glambdastar^(1-(1-gphi)*galpha)*(glambdaq)^(-(1-gphi)*galpha);</code></p>
<p>And I can not figure out how to convert that line to:</p>
<p><code>pow(glambdastar,(1-(1-gphi)*galpha))*pow(glambdaq,-(1-gphi)*galpha));</code></p>
| 2
|
2009-03-13T15:14:07Z
| 643,219
|
<p>See recent discussion <a href="http://stackoverflow.com/questions/637773/function-parser-with-regex-in-python">function-parser-with-regex-in-python</a> (one of many similar discussions). Then follow the suggestion to <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a>.</p>
| 0
|
2009-03-13T15:23:50Z
|
[
"python",
"c",
"regex"
] |
regular expression help with converting exp1^exp2 to pow(exp1, exp2)
| 643,173
|
<p>I am converting some matlab code to C, currently I have some lines that have powers using the ^, which is rather easy to do with something along the lines <code>\(?(\w*)\)?\^\(?(\w*)\)?</code></p>
<p>works fine for converting <code>(glambda)^(galpha)</code>,using the sub routine in python <code>pattern.sub(pow(\g<1>,\g<2>),'(glambda)^(galpha)')</code></p>
<p>My problem comes with nested parenthesis</p>
<p>So I have a string like:</p>
<p><code>glambdastar^(1-(1-gphi)*galpha)*(glambdaq)^(-(1-gphi)*galpha);</code></p>
<p>And I can not figure out how to convert that line to:</p>
<p><code>pow(glambdastar,(1-(1-gphi)*galpha))*pow(glambdaq,-(1-gphi)*galpha));</code></p>
| 2
|
2009-03-13T15:14:07Z
| 643,220
|
<p>An alternative would be to iterate until all ^ have been exhausted. no?.</p>
<p>Ruby code:</p>
<pre><code># assuming str contains the string of data with the expressions you wish to convert
while str.include?('^')
str!.gsub!(/(\w+)\^(\w+)/, 'pow(\1,\2)')
end
</code></pre>
| 0
|
2009-03-13T15:23:58Z
|
[
"python",
"c",
"regex"
] |
regular expression help with converting exp1^exp2 to pow(exp1, exp2)
| 643,173
|
<p>I am converting some matlab code to C, currently I have some lines that have powers using the ^, which is rather easy to do with something along the lines <code>\(?(\w*)\)?\^\(?(\w*)\)?</code></p>
<p>works fine for converting <code>(glambda)^(galpha)</code>,using the sub routine in python <code>pattern.sub(pow(\g<1>,\g<2>),'(glambda)^(galpha)')</code></p>
<p>My problem comes with nested parenthesis</p>
<p>So I have a string like:</p>
<p><code>glambdastar^(1-(1-gphi)*galpha)*(glambdaq)^(-(1-gphi)*galpha);</code></p>
<p>And I can not figure out how to convert that line to:</p>
<p><code>pow(glambdastar,(1-(1-gphi)*galpha))*pow(glambdaq,-(1-gphi)*galpha));</code></p>
| 2
|
2009-03-13T15:14:07Z
| 643,252
|
<p>I think you can use recursion here.</p>
<p>Once you figure out the Left and Right parts, pass each of those to your function again.
The base case would be that no ^ operator is found, so you will not need to add the pow() function to your result string.</p>
<p>The function will return a string with all the correct pow()'s in place.
I'll come up with an example of this if you want.</p>
| 1
|
2009-03-13T15:30:57Z
|
[
"python",
"c",
"regex"
] |
How can I auto-fill a paragraph in Eclipse?
| 643,422
|
<p>I would like to auto-fill a paragraph to 80 characters (or some other fixed width) in Eclipse. Is this possible via a keyboard command like in Emacs? Or is there maybe a plugin (I did not find anything on google)?</p>
<p>Edit: I am not sure if this is relevant, but I need this for docstrings in Python code (using the PyDev plugin).</p>
| 2
|
2009-03-13T16:05:51Z
| 643,439
|
<p>Highlight the text, then press Ctrl-Shift-F, or open the context menu and select Source / Format.</p>
| 2
|
2009-03-13T16:08:40Z
|
[
"python",
"eclipse",
"formatting",
"wrapping"
] |
How can I auto-fill a paragraph in Eclipse?
| 643,422
|
<p>I would like to auto-fill a paragraph to 80 characters (or some other fixed width) in Eclipse. Is this possible via a keyboard command like in Emacs? Or is there maybe a plugin (I did not find anything on google)?</p>
<p>Edit: I am not sure if this is relevant, but I need this for docstrings in Python code (using the PyDev plugin).</p>
| 2
|
2009-03-13T16:05:51Z
| 2,016,824
|
<p>You can wrap the paragraph in Pydev with Ctrl+2+w (see Pydev keybindings at: <a href="http://pydev.org/manual_adv_keybindings.html">http://pydev.org/manual_adv_keybindings.html</a>)</p>
| 6
|
2010-01-06T22:31:20Z
|
[
"python",
"eclipse",
"formatting",
"wrapping"
] |
How can I use numpy.correlate to do autocorrelation?
| 643,699
|
<p>I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. </p>
<p>I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is <em>not</em> the largest, as it ought to be.</p>
<p>So, this question is really two questions:</p>
<ol>
<li>What exactly is numpy.correlate doing?</li>
<li>How can I use it (or something else) to do auto-correlation?</li>
</ol>
| 52
|
2009-03-13T17:07:53Z
| 654,405
|
<p>1) Here is the documentation for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html" rel="nofollow">numpy.correlate</a>. The code inside the file looks like this:</p>
<pre><code>mode = _mode_from_name(mode)
return multiarray.correlate(a,v,mode)
</code></pre>
<p><code>multiarray.correlate</code> points to a .pyd file (i.e. a DLL file), so to get the inner workings you should probably ask the numpy developers.</p>
<p>2) If you don't believe the numpy results, you might try <a href="http://www.scipy.org/doc/api%5Fdocs/SciPy.signal.signaltools.html#correlate" rel="nofollow">SciPy's correlate function</a>. </p>
| -5
|
2009-03-17T14:04:06Z
|
[
"python",
"math",
"numpy",
"numerical-methods"
] |
How can I use numpy.correlate to do autocorrelation?
| 643,699
|
<p>I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. </p>
<p>I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is <em>not</em> the largest, as it ought to be.</p>
<p>So, this question is really two questions:</p>
<ol>
<li>What exactly is numpy.correlate doing?</li>
<li>How can I use it (or something else) to do auto-correlation?</li>
</ol>
| 52
|
2009-03-13T17:07:53Z
| 676,302
|
<p>To answer your first question, <code>numpy.correlate(a, v, mode)</code> is performing the convolution of <code>a</code> with the reverse of <code>v</code> and giving the results clipped by the specified mode. The <a href="http://mathworld.wolfram.com/Convolution.html">definition of convolution</a>, C(t)=â <sub>-â < i < â </sub> a<sub>i</sub>v<sub>t+i</sub> where -â < t < â, allows for results from -â to â, but you obviously can't store an infinitely long array. So it has to be clipped, and that is where the mode comes in. There are 3 different modes: full, same, & valid: </p>
<ul>
<li>"full" mode returns results for every <code>t</code> where both <code>a</code> and <code>v</code> have some overlap. </li>
<li>"same" mode returns a result with the same length as the shortest vector (<code>a</code> or <code>v</code>). </li>
<li>"valid" mode returns results only when <code>a</code> and <code>v</code> completely overlap each other. The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html">documentation</a> for <code>numpy.convolve</code> gives more detail on the modes.</li>
</ul>
<p>For your second question, I think <code>numpy.correlate</code> <em>is</em> giving you the autocorrelation, it is just giving you a little more as well. The autocorrelation is used to find how similar a signal, or function, is to itself at a certain time difference. At a time difference of 0, the auto-correlation should be the highest because the signal is identical to itself, so you expected that the first element in the autocorrelation result array would be the greatest. However, the correlation is not starting at a time difference of 0. It starts at a negative time difference, closes to 0, and then goes positive. That is, you were expecting: </p>
<p>autocorrelation(a) = â <sub>-â < i < â </sub> a<sub>i</sub>v<sub>t+i</sub> where 0 <= t < â </p>
<p>But what you got was: </p>
<p>autocorrelation(a) = â <sub>-â < i < â </sub> a<sub>i</sub>v<sub>t+i</sub> where -â < t < â</p>
<p>What you need to do is take the last half of your correlation result, and that should be the autocorrelation you are looking for. A simple python function to do that would be:</p>
<pre><code>def autocorr(x):
result = numpy.correlate(x, x, mode='full')
return result[result.size/2:]
</code></pre>
<p>You will, of course, need error checking to make sure that <code>x</code> is actually a 1-d array. Also, this explanation probably isn't the most mathematically rigorous. I've been throwing around infinities because the definition of convolution uses them, but that doesn't necessarily apply for autocorrelation. So, the theoretical portion of this explanation may be slightly wonky, but hopefully the practical results are helpful. <a href="http://mathworld.wolfram.com/Autocorrelation.html">These</a> <a href="http://en.wikipedia.org/wiki/Autocorrelation">pages</a> on autocorrelation are pretty helpful, and can give you a much better theoretical background if you don't mind wading through the notation and heavy concepts.</p>
| 57
|
2009-03-24T06:09:02Z
|
[
"python",
"math",
"numpy",
"numerical-methods"
] |
How can I use numpy.correlate to do autocorrelation?
| 643,699
|
<p>I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. </p>
<p>I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is <em>not</em> the largest, as it ought to be.</p>
<p>So, this question is really two questions:</p>
<ol>
<li>What exactly is numpy.correlate doing?</li>
<li>How can I use it (or something else) to do auto-correlation?</li>
</ol>
| 52
|
2009-03-13T17:07:53Z
| 7,981,132
|
<p>Auto-correlation comes in two versions: statistical and convolution. They both do the same, except for a little detail: The former is normalized to be on the interval [-1,1]. Here is an example of how you do the statistical one:</p>
<pre><code>def acf(x, length=20):
return numpy.array([1]+[numpy.corrcoef(x[:-i], x[i:]) \
for i in range(1, length)])
</code></pre>
| 10
|
2011-11-02T13:27:37Z
|
[
"python",
"math",
"numpy",
"numerical-methods"
] |
How can I use numpy.correlate to do autocorrelation?
| 643,699
|
<p>I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. </p>
<p>I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is <em>not</em> the largest, as it ought to be.</p>
<p>So, this question is really two questions:</p>
<ol>
<li>What exactly is numpy.correlate doing?</li>
<li>How can I use it (or something else) to do auto-correlation?</li>
</ol>
| 52
|
2009-03-13T17:07:53Z
| 17,090,200
|
<p>As I just ran into the same problem, I would like to share a few lines of code with you. In fact there are several rather similar posts about autocorrelation in stackoverflow by now. If you define the autocorrelation as <code>a(x, L) = sum(k=0,N-L-1)((xk-xbar)*(x(k+L)-xbar))/sum(k=0,N-1)((xk-xbar)**2)</code> [this is the definition given in IDL's a_correlate function and it agrees with what I see in answer 2 of question <a href="http://stackoverflow.com/questions/12269834/is-there-any-numpy-autocorrellation-function-with-standardized-output">#12269834</a>], then the following seems to give the correct results:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0.,6.12,0.01)
y = np.sin(x)
# y = np.random.uniform(size=300)
yunbiased = y-np.mean(y)
ynorm = np.sum(yunbiased**2)
acor = np.correlate(yunbiased, yunbiased, "same")/ynorm
# use only second half
acor = acor[len(acor)/2:]
plt.plot(acor)
plt.show()
</code></pre>
<p>As you see I have tested this with a sin curve and a uniform random distribution, and both results look like I would expect them. Note that I used <code>mode="same"</code> instead of <code>mode="full"</code> as the others did. </p>
| 7
|
2013-06-13T14:52:10Z
|
[
"python",
"math",
"numpy",
"numerical-methods"
] |
How can I use numpy.correlate to do autocorrelation?
| 643,699
|
<p>I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. </p>
<p>I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is <em>not</em> the largest, as it ought to be.</p>
<p>So, this question is really two questions:</p>
<ol>
<li>What exactly is numpy.correlate doing?</li>
<li>How can I use it (or something else) to do auto-correlation?</li>
</ol>
| 52
|
2009-03-13T17:07:53Z
| 21,863,139
|
<p>Using the <code>numpy.corrcoef</code> function instead of <code>numpy.correlate</code> to calculate the statistical correlation for a lag of t:</p>
<pre><code>def autocorr(x, t=1):
numpy.corrcoef(numpy.array([x[0:len(x)-t], x[t:len(x)]]))
</code></pre>
| 10
|
2014-02-18T19:10:37Z
|
[
"python",
"math",
"numpy",
"numerical-methods"
] |
How can I use numpy.correlate to do autocorrelation?
| 643,699
|
<p>I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. </p>
<p>I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is <em>not</em> the largest, as it ought to be.</p>
<p>So, this question is really two questions:</p>
<ol>
<li>What exactly is numpy.correlate doing?</li>
<li>How can I use it (or something else) to do auto-correlation?</li>
</ol>
| 52
|
2009-03-13T17:07:53Z
| 28,268,013
|
<p>I think the real answer to the OP's question is succinctly contained in this excerpt from the Numpy.correlate documentation:</p>
<pre><code>mode : {'valid', 'same', 'full'}, optional
Refer to the `convolve` docstring. Note that the default
is `valid`, unlike `convolve`, which uses `full`.
</code></pre>
<p>This implies that, when used with no 'mode' definition, the Numpy.correlate function will return a scalar, when given the same vector for its two input arguments (i.e. - when used to perform autocorrelation).</p>
| 0
|
2015-02-01T21:17:42Z
|
[
"python",
"math",
"numpy",
"numerical-methods"
] |
How can I use numpy.correlate to do autocorrelation?
| 643,699
|
<p>I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. </p>
<p>I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is <em>not</em> the largest, as it ought to be.</p>
<p>So, this question is really two questions:</p>
<ol>
<li>What exactly is numpy.correlate doing?</li>
<li>How can I use it (or something else) to do auto-correlation?</li>
</ol>
| 52
|
2009-03-13T17:07:53Z
| 34,408,787
|
<p>I use talib.CORREL for autocorrelation like this, I suspect you could do the same with other packages:</p>
<pre><code>def autocorrelate(x, period):
# x is a deep indicator array
# period of sample and slices of comparison
# oldest data (period of input array) may be nan; remove it
x = x[-np.count_nonzero(~np.isnan(x)):]
# subtract mean to normalize indicator
x -= np.mean(x)
# isolate the recent sample to be autocorrelated
sample = x[-period:]
# create slices of indicator data
correls = []
for n in range((len(x)-1), period, -1):
alpha = period + n
slices = (x[-alpha:])[:period]
# compare each slice to the recent sample
correls.append(ta.CORREL(slices, sample, period)[-1])
# fill in zeros for sample overlap period of recent correlations
for n in range(period,0,-1):
correls.append(0)
# oldest data (autocorrelation period) will be nan; remove it
correls = np.array(correls[-np.count_nonzero(~np.isnan(correls)):])
return correls
# CORRELATION OF BEST FIT
# the highest value correlation
max_value = np.max(correls)
# index of the best correlation
max_index = np.argmax(correls)
</code></pre>
| 0
|
2015-12-22T05:06:48Z
|
[
"python",
"math",
"numpy",
"numerical-methods"
] |
Does python's pip support http authentication?
| 643,756
|
<p>As the title says, does pip support http authentication, like easy_install does?</p>
<p>If not, are there any (better) alternatives to running a private package repository? I see pip can access source repositories (git,svn etc.), but can version requirements be used with this?</p>
| 3
|
2009-03-13T17:25:56Z
| 705,306
|
<p>pip <a href="http://oss.openplans.org/pip/browser/pip/trunk/pip.py" rel="nofollow">uses</a> urllib2.urlopen() to fetch files. urllib2.urlopen() supports HTTP authentication, but pip doesn't appear to install the HTTPBasicAuthHandler when it builds its opener. Adding such support would be trivial; you could either parse the URL for user:password or accept the same information as command line parameters. <a href="http://feedparser.org/docs/http-authentication.html" rel="nofollow">feedparser</a> supports both methods by <a href="http://code.google.com/p/feedparser/source/browse/trunk/feedparser/feedparser.py" rel="nofollow">subclassing</a> urllib2.HTTPDigestAuthHandler.</p>
| 3
|
2009-04-01T12:42:13Z
|
[
"python",
"easy-install",
"pip"
] |
Does python's pip support http authentication?
| 643,756
|
<p>As the title says, does pip support http authentication, like easy_install does?</p>
<p>If not, are there any (better) alternatives to running a private package repository? I see pip can access source repositories (git,svn etc.), but can version requirements be used with this?</p>
| 3
|
2009-03-13T17:25:56Z
| 1,250,775
|
<p>Currently simply pip does not support authentication.</p>
<p>But <a href="http://groups.google.com/group/python-virtualenv/msg/7aff34d86c595f84" rel="nofollow">the main author of pip thinks that feature is desirable</a> so probably it will appear in the medium future. There is also <a href="http://projects.openplans.org/pip/ticket/30" rel="nofollow">an item in the PIP trac</a> containing a patch to enable http auth.</p>
| 2
|
2009-08-09T06:00:47Z
|
[
"python",
"easy-install",
"pip"
] |
Does python's pip support http authentication?
| 643,756
|
<p>As the title says, does pip support http authentication, like easy_install does?</p>
<p>If not, are there any (better) alternatives to running a private package repository? I see pip can access source repositories (git,svn etc.), but can version requirements be used with this?</p>
| 3
|
2009-03-13T17:25:56Z
| 1,778,803
|
<p>FYI, it's currently being worked on in the <a href="http://github.com/brosner/pip/tree/http%5Fauth%5Findex" rel="nofollow" title="http_auth_index"><code>http_auth_index</code></a> branch which will allow the use of basic auth for custom indexes.</p>
| 2
|
2009-11-22T14:09:24Z
|
[
"python",
"easy-install",
"pip"
] |
Does python's pip support http authentication?
| 643,756
|
<p>As the title says, does pip support http authentication, like easy_install does?</p>
<p>If not, are there any (better) alternatives to running a private package repository? I see pip can access source repositories (git,svn etc.), but can version requirements be used with this?</p>
| 3
|
2009-03-13T17:25:56Z
| 22,031,917
|
<p>For people still searching for an answer you can use the following syntax:</p>
<pre><code>pip install -r https://user:pass@domain.com/path/requirements.txt
</code></pre>
<p>An also if you require to validate their certificate use:</p>
<pre><code>pip install --cert host.pem -r https://user:pass@domain.com/path/requirements.txt
</code></pre>
<p>This is working on:</p>
<pre><code>$ pip --version
pip 1.5.4 from /usr/local/lib/python2.7/dist-packages (python 2.7)
</code></pre>
<p>To upgrade your pip do:</p>
<pre><code>pip install --upgrade pip
</code></pre>
| 3
|
2014-02-26T04:42:16Z
|
[
"python",
"easy-install",
"pip"
] |
Python - list transformation
| 643,823
|
<p>Does anyone knows what magic I have to use to change x list: </p>
<blockquote>
<p>x = [1,2,3,4,5,11]</p>
</blockquote>
<p>into y list?</p>
<blockquote>
<p>y = ['01','02','03','04','05','11']</p>
</blockquote>
<p>Thank you all in advance for helping me...</p>
| 13
|
2009-03-13T17:41:29Z
| 643,825
|
<p>You want to use the built-in <a href="http://docs.python.org/library/functions.html#map"><code>map</code></a> function:</p>
<pre><code>>>> x = [1,2,3,4,5]
>>> x
[1, 2, 3, 4, 5]
>>> y = map(str, x)
>>> y
['1', '2', '3', '4', '5']
</code></pre>
<p><strong>EDIT</strong> You changed the requirements on me! To make it display leading zeros, you do this:</p>
<pre><code>>>> x = [1,2,3,4,5,11]
>>> y = ["%02d" % v for v in x]
>>> y
['01', '02', '03', '04', '05', '11']
</code></pre>
| 13
|
2009-03-13T17:42:44Z
|
[
"python",
"list"
] |
Python - list transformation
| 643,823
|
<p>Does anyone knows what magic I have to use to change x list: </p>
<blockquote>
<p>x = [1,2,3,4,5,11]</p>
</blockquote>
<p>into y list?</p>
<blockquote>
<p>y = ['01','02','03','04','05','11']</p>
</blockquote>
<p>Thank you all in advance for helping me...</p>
| 13
|
2009-03-13T17:41:29Z
| 643,830
|
<p>You can use a list comprehension (Python 2.6+):</p>
<pre><code>y = ["{0:0>2}".format(v) for v in x]
</code></pre>
<p>Or for Python prior to 2.6:</p>
<pre><code>y = ["%02d" % v for v in x]
</code></pre>
<p>Edit: Missed the fact that you wanted zero-padding...</p>
| 29
|
2009-03-13T17:45:20Z
|
[
"python",
"list"
] |
Python - list transformation
| 643,823
|
<p>Does anyone knows what magic I have to use to change x list: </p>
<blockquote>
<p>x = [1,2,3,4,5,11]</p>
</blockquote>
<p>into y list?</p>
<blockquote>
<p>y = ['01','02','03','04','05','11']</p>
</blockquote>
<p>Thank you all in advance for helping me...</p>
| 13
|
2009-03-13T17:41:29Z
| 643,843
|
<p>to get the 0's:</p>
<pre><code>y = ['%02d' % i for i in x]
</code></pre>
| 0
|
2009-03-13T17:49:41Z
|
[
"python",
"list"
] |
Python - list transformation
| 643,823
|
<p>Does anyone knows what magic I have to use to change x list: </p>
<blockquote>
<p>x = [1,2,3,4,5,11]</p>
</blockquote>
<p>into y list?</p>
<blockquote>
<p>y = ['01','02','03','04','05','11']</p>
</blockquote>
<p>Thank you all in advance for helping me...</p>
| 13
|
2009-03-13T17:41:29Z
| 643,846
|
<pre><code>y = ['%02d'%v for v in x]
</code></pre>
| 0
|
2009-03-13T17:51:02Z
|
[
"python",
"list"
] |
Python - list transformation
| 643,823
|
<p>Does anyone knows what magic I have to use to change x list: </p>
<blockquote>
<p>x = [1,2,3,4,5,11]</p>
</blockquote>
<p>into y list?</p>
<blockquote>
<p>y = ['01','02','03','04','05','11']</p>
</blockquote>
<p>Thank you all in advance for helping me...</p>
| 13
|
2009-03-13T17:41:29Z
| 643,847
|
<p>I would use a list comprehension myself, but here is another solution using map for those interested...</p>
<pre><code>map(lambda v: "%02d" %v, x)
</code></pre>
| 5
|
2009-03-13T17:51:19Z
|
[
"python",
"list"
] |
Python - list transformation
| 643,823
|
<p>Does anyone knows what magic I have to use to change x list: </p>
<blockquote>
<p>x = [1,2,3,4,5,11]</p>
</blockquote>
<p>into y list?</p>
<blockquote>
<p>y = ['01','02','03','04','05','11']</p>
</blockquote>
<p>Thank you all in advance for helping me...</p>
| 13
|
2009-03-13T17:41:29Z
| 646,037
|
<p>An alternative to format strings would be to use the string's zfill() method:</p>
<pre><code>y = [str(i).zfill(2) for i in x]
</code></pre>
<p>Another thing: you might be after padding based on the largest item in the list, so instead of just using 2, you could do:</p>
<pre><code>pad_length = len(str(max(x)))
y = [str(i).zfill(pad_length) for i in x]
</code></pre>
| 0
|
2009-03-14T15:02:14Z
|
[
"python",
"list"
] |
Using "like" in a cursor/query with a parameter in python (django)
| 643,930
|
<p>I know this may be something stupid but I decided to ask any way.</p>
<p>I've been trying to query something like:</p>
<pre><code> cursor.execute("select col1, col2 \
from my_tablem \
where afield like '%%s%'
and secondfield = %s
order by 1 desc " % (var1, var2) )
</code></pre>
<p>But I get an error in the like sentence. It doesn't like the extra % which I need to get all the results that contains the first %s value.</p>
<p>Ideas?</p>
<p>TIA! </p>
| 4
|
2009-03-13T18:14:21Z
| 644,043
|
<p>First, why aren't you using the Django ORM for this?</p>
<pre><code>MyClass.objects.filter( aField__contains=var1, secondField__exact=var2 )
</code></pre>
<p>Second, be sure you're getting the SQL you expect.</p>
<pre><code>stmt= "select... afield like '%%%s%%' and secondfield = '%s'..." % ( var1, var2 )
print stmt
cursor.execute( stmt )
</code></pre>
<p>Third, your method has a security hole called a SQL Injection Attack. You really should not be doing SQL like this.</p>
<p>If you absolutely must do things outside Django's ORM, you have to use bind variables in your query, not string substitution. See <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-sql-queries">http://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-sql-queries</a>.</p>
| 7
|
2009-03-13T18:32:31Z
|
[
"python",
"sql",
"django",
"cursor",
"like"
] |
Using "like" in a cursor/query with a parameter in python (django)
| 643,930
|
<p>I know this may be something stupid but I decided to ask any way.</p>
<p>I've been trying to query something like:</p>
<pre><code> cursor.execute("select col1, col2 \
from my_tablem \
where afield like '%%s%'
and secondfield = %s
order by 1 desc " % (var1, var2) )
</code></pre>
<p>But I get an error in the like sentence. It doesn't like the extra % which I need to get all the results that contains the first %s value.</p>
<p>Ideas?</p>
<p>TIA! </p>
| 4
|
2009-03-13T18:14:21Z
| 3,173,197
|
<p>can hack string '%' into search string?</p>
<pre><code>var1 = '%' + var1 + '%'
then query normally:
cursor.execute("select col1, col2
from my_tablem where afield like %s
and secondfield = %s
order by 1 desc " , [var1, var2] )
</code></pre>
| 5
|
2010-07-03T23:32:09Z
|
[
"python",
"sql",
"django",
"cursor",
"like"
] |
Using "like" in a cursor/query with a parameter in python (django)
| 643,930
|
<p>I know this may be something stupid but I decided to ask any way.</p>
<p>I've been trying to query something like:</p>
<pre><code> cursor.execute("select col1, col2 \
from my_tablem \
where afield like '%%s%'
and secondfield = %s
order by 1 desc " % (var1, var2) )
</code></pre>
<p>But I get an error in the like sentence. It doesn't like the extra % which I need to get all the results that contains the first %s value.</p>
<p>Ideas?</p>
<p>TIA! </p>
| 4
|
2009-03-13T18:14:21Z
| 4,587,056
|
<p>I had a similar issue. I was trying to search among concatenated name fields. My query was something like:</p>
<pre><code>sql = """SELECT * from auth_user WHERE lower(first_name) || ' ' || lower(last_name) = '%%%s%%'"""
User.objects.raw(sql, [q])
</code></pre>
<p>The problem was that the %% were breaking my query. The solution I wound up with was:</p>
<pre><code>q = '%' + q + '%'
sql = """SELECT * from auth_user WHERE lower(first_name) || ' ' || lower(last_name) = %s"""
User.objects.raw(sql, [q])
</code></pre>
| 3
|
2011-01-03T18:15:59Z
|
[
"python",
"sql",
"django",
"cursor",
"like"
] |
Using "like" in a cursor/query with a parameter in python (django)
| 643,930
|
<p>I know this may be something stupid but I decided to ask any way.</p>
<p>I've been trying to query something like:</p>
<pre><code> cursor.execute("select col1, col2 \
from my_tablem \
where afield like '%%s%'
and secondfield = %s
order by 1 desc " % (var1, var2) )
</code></pre>
<p>But I get an error in the like sentence. It doesn't like the extra % which I need to get all the results that contains the first %s value.</p>
<p>Ideas?</p>
<p>TIA! </p>
| 4
|
2009-03-13T18:14:21Z
| 22,409,633
|
<pre><code>Persona.objects.raw("**SELECT** id,concat_ws(' ',nombre,apellido) **AS** nombre_completo **FROM** persona **GROUP BY** id **HAVING** concat_ws(' ',nombre,apellido) **ILIKE** '%s' " % ('%%' + query + '%%'))
</code></pre>
<p>(Postgresql 9.1)</p>
| 0
|
2014-03-14T15:42:07Z
|
[
"python",
"sql",
"django",
"cursor",
"like"
] |
How do I rewrite $x = $hash{blah} || 'default' in Python?
| 643,950
|
<p>How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do:</p>
<pre><code>$x = $hash{blah} || 'default'
</code></pre>
<p>What's the equivalent Python?</p>
| 3
|
2009-03-13T18:16:50Z
| 643,960
|
<p>Use the <a href="http://docs.python.org/library/stdtypes.html#dict.get" rel="nofollow"><code>get(key, default)</code></a> method:</p>
<pre><code>>>> dict().get("blah", "default")
'default'
</code></pre>
| 9
|
2009-03-13T18:19:21Z
|
[
"python"
] |
How do I rewrite $x = $hash{blah} || 'default' in Python?
| 643,950
|
<p>How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do:</p>
<pre><code>$x = $hash{blah} || 'default'
</code></pre>
<p>What's the equivalent Python?</p>
| 3
|
2009-03-13T18:16:50Z
| 643,961
|
<pre><code>x = hash['blah'] if 'blah' in hash else 'default'
</code></pre>
| 1
|
2009-03-13T18:19:23Z
|
[
"python"
] |
How do I rewrite $x = $hash{blah} || 'default' in Python?
| 643,950
|
<p>How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do:</p>
<pre><code>$x = $hash{blah} || 'default'
</code></pre>
<p>What's the equivalent Python?</p>
| 3
|
2009-03-13T18:16:50Z
| 643,969
|
<pre><code>x = hash.has_key('blah') and hash['blah'] or 'default'
</code></pre>
| 0
|
2009-03-13T18:21:09Z
|
[
"python"
] |
How do I rewrite $x = $hash{blah} || 'default' in Python?
| 643,950
|
<p>How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do:</p>
<pre><code>$x = $hash{blah} || 'default'
</code></pre>
<p>What's the equivalent Python?</p>
| 3
|
2009-03-13T18:16:50Z
| 644,007
|
<p>If you're going to be doing this a lot, it's better to use <a href="http://docs.python.org/library/collections.html#collections.defaultdict" rel="nofollow">collections.defaultdict</a>:</p>
<pre><code>import collections
# Define a little "factory" function that just builds the default value when called.
def get_default_value():
return 'default'
# Create a defaultdict, specifying the factory that builds its default value
dict = collections.defaultdict(get_default_value)
# Now we can look up things without checking, and get 'default' if the key is unknown
x = dict['blah']
</code></pre>
| 7
|
2009-03-13T18:26:11Z
|
[
"python"
] |
Concurrency implications of EAFP/LBYL
| 644,052
|
<p>When writing concurrent/multithreaded code in Python, is it especially important to follow the "Easier to Ask for Forgiveness than Permission" (EAFP) idiom, rather than "Look Before You Leap" (LBYL)? Python's exceptionally dynamic nature means that almost anything (e.g., attribute removal) can happen between looking and leaping---if so, what's the point? For example, consider</p>
<pre><code># LBYL
if hasattr(foo, 'bar'):
baz = foo.bar
</code></pre>
<p>versus</p>
<pre><code># EAFP
try:
baz = foo.bar
except AttributeError:
pass
</code></pre>
<p>In the LBYL example, the <code>bar</code> attribute could disappear from <code>foo</code> before the actual call to <code>foo.bar</code> is made, so do you gain anything from the check? If there's a risk the attribute might disappear, you need locks and/or try/except clauses anyway.</p>
<p>One possible argument here is that this example makes the extremely pessimistic assumption that "antagonistic code" is running that could yank the rug from under you at any moment. In most use cases, this is highly unlikely.</p>
| 3
|
2009-03-13T18:33:59Z
| 644,407
|
<p>Your thoughts are correct. Some additional points:</p>
<p>If the attribute exists most of the time, try:except: might be much faster than
the LBYL idiom.</p>
<p>If you don't like the try: except: syntax, you can also write:</p>
<pre><code>item = getattr(foo, 'bar', None)
if item is None:
....
else:
....
</code></pre>
| 3
|
2009-03-13T20:07:45Z
|
[
"python",
"multithreading"
] |
How should I conditionally assign based on the existence of a dictionary key?
| 644,062
|
<p>I've got some Perl code like this:</p>
<pre><code>my $match = $matches{$key}
? "$matches{$key} was a match!"
: "There was no match."
</code></pre>
<p>How is this best rewritten in Python? I'm trying to avoid getting a KeyError.</p>
| 1
|
2009-03-13T18:35:33Z
| 644,072
|
<p>This.</p>
<pre><code>message = "%s was a match"%(matches[key],) if key in matches else "There was no match."
</code></pre>
| 3
|
2009-03-13T18:40:39Z
|
[
"python"
] |
signal.alarm replacement in Windows [Python]
| 644,073
|
<p>I have a function that occasionally hangs.</p>
<p>Normally I would set an alarm, but I'm in Windows and it's unavailable.</p>
<p>Is there a simple way around this, or should I just create a thread that calls <code>time.sleep()</code>?</p>
| 11
|
2009-03-13T18:40:41Z
| 644,252
|
<p>You could - as you mentioned - just kick off a new thread that sleeps for that number of seconds.</p>
<p>Or you can use one of Windows' multimedia timers (in Python, that'd be in windll.winmm). I believe <code>timeSetEvent</code> is what you're looking for. Incidentally, I found a piece of code that uses it <a href="http://osdir.com/ml/python.ctypes/2007-11/msg00024.html" rel="nofollow">here</a>.</p>
| 2
|
2009-03-13T19:27:50Z
|
[
"python",
"alarm"
] |
signal.alarm replacement in Windows [Python]
| 644,073
|
<p>I have a function that occasionally hangs.</p>
<p>Normally I would set an alarm, but I'm in Windows and it's unavailable.</p>
<p>Is there a simple way around this, or should I just create a thread that calls <code>time.sleep()</code>?</p>
| 11
|
2009-03-13T18:40:41Z
| 699,105
|
<p>The most robust solution is to use a subprocess, then kill that subprocess. Python2.6 adds .kill() to subprocess.Popen().</p>
<p>I don't think your threading approach works as you expect. Deleting your reference to the Thread object won't kill the thread. Instead, you'd need to set an attribute that the thread checks once it wakes up.</p>
| 3
|
2009-03-30T21:26:04Z
|
[
"python",
"alarm"
] |
signal.alarm replacement in Windows [Python]
| 644,073
|
<p>I have a function that occasionally hangs.</p>
<p>Normally I would set an alarm, but I'm in Windows and it's unavailable.</p>
<p>Is there a simple way around this, or should I just create a thread that calls <code>time.sleep()</code>?</p>
| 11
|
2009-03-13T18:40:41Z
| 31,671,095
|
<p>Here's how the original poster solved his own problem:</p>
<p>Ended up going with a thread. Only trick was using <code>os._exit</code> instead of <code>sys.exit</code></p>
<pre><code>import os
import time
import threading
class Alarm (threading.Thread):
def __init__ (self, timeout):
threading.Thread.__init__ (self)
self.timeout = timeout
self.setDaemon (True)
def run (self):
time.sleep (self.timeout)
os._exit (1)
alarm = Alarm (4)
alarm.start ()
time.sleep (2)
del alarm
print 'yup'
alarm = Alarm (4)
alarm.start ()
time.sleep (8)
del alarm
print 'nope' # we don't make it this far
</code></pre>
| 1
|
2015-07-28T08:29:22Z
|
[
"python",
"alarm"
] |
help with complex join in Django ORM
| 644,081
|
<pre><code>class Domains(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length= 60)
user = models.ManyToManyField("Users", blank=True, null=True)
def __unicode__(self):
return self.name
class Groups(models.Model):
domain = models.ForeignKey(Domains)
name = models.CharField(max_length=30)
description = models.CharField(max_length= 60)
def __unicode__(self):
return self.name
class Users(models.Model):
login = models.CharField(max_length=30, unique=True)
group = models.ManyToManyField(Groups, blank=True, null=True)
def __unicode__(self):
return self.login
</code></pre>
<p>I have the model above. Needed some assistance working with Django ORM.
How would I build a query the returns all the Group names that belong to only those Domains to which a User belongs</p>
| 3
|
2009-03-13T18:44:08Z
| 644,244
|
<p>You should probably use singular names for your model classes. For example, I'd rewrite the models as:</p>
<pre><code>class Domain(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length= 60)
user = models.ManyToManyField('User', blank=True, null=True)
def __unicode__(self):
return self.name
class Group(models.Model):
domain = models.ForeignKey(Domain, related_name='groups')
name = models.CharField(max_length=30)
description = models.CharField(max_length= 60)
def __unicode__(self):
return self.name
class User(models.Model):
login = models.CharField(max_length=30, unique=True)
group = models.ManyToManyField(Group, related_name='users', blank=True, null=True)
def __unicode__(self):
return self.login
</code></pre>
<p>Since you have users directly related to groups, you don't need to involve domains at all. To fetch all group names for a particular user, you'd do:</p>
<pre><code>Group.objects.filter(users__pk=...).values_list('name', flat=True)
</code></pre>
<p>Replace '...' with the ID of the user you're interested in.</p>
| 2
|
2009-03-13T19:26:45Z
|
[
"python",
"django",
"django-models"
] |
help with complex join in Django ORM
| 644,081
|
<pre><code>class Domains(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length= 60)
user = models.ManyToManyField("Users", blank=True, null=True)
def __unicode__(self):
return self.name
class Groups(models.Model):
domain = models.ForeignKey(Domains)
name = models.CharField(max_length=30)
description = models.CharField(max_length= 60)
def __unicode__(self):
return self.name
class Users(models.Model):
login = models.CharField(max_length=30, unique=True)
group = models.ManyToManyField(Groups, blank=True, null=True)
def __unicode__(self):
return self.login
</code></pre>
<p>I have the model above. Needed some assistance working with Django ORM.
How would I build a query the returns all the Group names that belong to only those Domains to which a User belongs</p>
| 3
|
2009-03-13T18:44:08Z
| 644,275
|
<p>I second elo80ka's comment about using singular names for your models. To filter the groups by domain and user, try:</p>
<pre><code>Groups.objects.filter(domain__user=u)
</code></pre>
<p>This will perform the appropriate join across the many-to-many. As written, the query will return group objects. If you want the name property only, then append the <code>.values_list('name', flat=True)</code> to the query as elo80ka suggests.</p>
| 4
|
2009-03-13T19:32:04Z
|
[
"python",
"django",
"django-models"
] |
How does Python sort a list of tuples?
| 644,170
|
<p>Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?</p>
| 45
|
2009-03-13T19:09:17Z
| 644,183
|
<p>Yes, this is the default. In fact, this is the basis of the classic "DSU" (Decorate-Sort-Undecorate) idiom in Python. See <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html">Code Like a Pythonista</a>.</p>
| 8
|
2009-03-13T19:12:54Z
|
[
"python"
] |
How does Python sort a list of tuples?
| 644,170
|
<p>Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?</p>
| 45
|
2009-03-13T19:09:17Z
| 644,189
|
<p>It automatically sorts a list of tuples by the first elements in the tuples, then by the second elements and so on tuple([1,2,3]) will go before tuple([1,2,4]). If you want to override this behaviour pass a callable as the second argument to the sort method. This callable should return 1, -1, 0.</p>
| 57
|
2009-03-13T19:13:49Z
|
[
"python"
] |
How does Python sort a list of tuples?
| 644,170
|
<p>Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?</p>
| 45
|
2009-03-13T19:09:17Z
| 644,190
|
<p>No, tuples are <a href="http://www.python.org/doc/2.5.2/lib/typesseq.html" rel="nofollow">sequence types</a> just like strings. They are sorted the same, by comparing each element in turn:</p>
<pre><code>>>> import random
>>> sorted([(0,0,0,int(random.getrandbits(4))) for x in xrange(10)])
[(0, 0, 0, 0), (0, 0, 0, 4), (0, 0, 0, 5), (0, 0, 0, 7), (0, 0, 0, 8),
(0, 0, 0, 9), (0, 0, 0, 12), (0, 0, 0, 12), (0, 0, 0, 12), (0, 0, 0, 14)]
</code></pre>
<p>The three zeroes are only there to show that something other than the first element must be getting inspected.</p>
| 4
|
2009-03-13T19:13:52Z
|
[
"python"
] |
How does Python sort a list of tuples?
| 644,170
|
<p>Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?</p>
| 45
|
2009-03-13T19:09:17Z
| 644,193
|
<p>Try using the internal list sort method and pass a lambda. If your tuples first element is a integer, this should work.</p>
<pre><code># l is the list of tuples
l.sort(lambda x,y: x-y)
</code></pre>
<p>You can use any callable for the compare function, not necessarily a lambda. However it needs to return -1 (less than), 0 (equal) or 1 (greater than).</p>
| 0
|
2009-03-13T19:14:36Z
|
[
"python"
] |
How does Python sort a list of tuples?
| 644,170
|
<p>Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?</p>
| 45
|
2009-03-13T19:09:17Z
| 644,574
|
<p>Check out "Devin Jeanpierre" answer to this question <a href="http://stackoverflow.com/questions/613183/sort-a-dictionary-in-python-by-the-value">sort-a-dictionary-in-python-by-the-value</a> where he says to use a tuple and shows how to sort by the second value</p>
| 0
|
2009-03-13T20:44:55Z
|
[
"python"
] |
How do I re-map python dict keys
| 644,178
|
<p>I am working on a program that (among other things) reads a CSV file in (it gets stored as an array of dicts in the form <code>[{col1:data1a,col2:data2a},{col1:data1b,col2:data2b}]</code> ). For each row, as part of other processing, I need to remap those keys to user entered values, which are provided in another dict so they can be used as parameters in an API call. The mapping array is in the form: <code>{badname1:goodname1, badname2:goodname2,...}</code>.</p>
<p>So I'd like to get from:
<code>{badname1:data1, badname2:data2,...}</code> to <code>{goodname1:data1, goodname2:data2,...}</code></p>
<p>I'd like to use something like <code>zip()</code> (although <code>zip()</code> yields <code>{badname1:badname1,...}</code>).</p>
<p>Seems like there should be an obvious solution that is alluding me.</p>
<p>EDIT:
If the data is in <code>a</code> and the mapping in <code>b</code>:</p>
<p><code>dict(zip(b,a.itervalues()))</code></p>
<p>I get close, but it will only work in cases where the fields are known to be in the same order I think.</p>
| 11
|
2009-03-13T19:11:21Z
| 644,314
|
<pre><code>name_map = {'oldcol1': 'newcol1', 'oldcol2': 'newcol2', 'oldcol3': 'newcol3'...}
for row in rows:
# Each row is a dict of the form: {'oldcol1': '...', 'oldcol2': '...'}
row = dict((name_map[name], val) for name, val in row.iteritems())
...
</code></pre>
<p>Or in Python2.7+ with <a href="http://www.python.org/dev/peps/pep-0274/">Dict Comprehensions</a>:</p>
<pre><code>for row in rows:
row = {name_map[name]: val for name, val in row.items()}
</code></pre>
| 14
|
2009-03-13T19:43:15Z
|
[
"python",
"dictionary"
] |
How do I re-map python dict keys
| 644,178
|
<p>I am working on a program that (among other things) reads a CSV file in (it gets stored as an array of dicts in the form <code>[{col1:data1a,col2:data2a},{col1:data1b,col2:data2b}]</code> ). For each row, as part of other processing, I need to remap those keys to user entered values, which are provided in another dict so they can be used as parameters in an API call. The mapping array is in the form: <code>{badname1:goodname1, badname2:goodname2,...}</code>.</p>
<p>So I'd like to get from:
<code>{badname1:data1, badname2:data2,...}</code> to <code>{goodname1:data1, goodname2:data2,...}</code></p>
<p>I'd like to use something like <code>zip()</code> (although <code>zip()</code> yields <code>{badname1:badname1,...}</code>).</p>
<p>Seems like there should be an obvious solution that is alluding me.</p>
<p>EDIT:
If the data is in <code>a</code> and the mapping in <code>b</code>:</p>
<p><code>dict(zip(b,a.itervalues()))</code></p>
<p>I get close, but it will only work in cases where the fields are known to be in the same order I think.</p>
| 11
|
2009-03-13T19:11:21Z
| 644,442
|
<pre><code>rows = [{"col1":"data1a","col2":"data2a"},{"col1":"data1b","col2":"data2b"}]
name_map = {"col1":"newcol1","col2":"newcol2"}
new_rows = [dict(zip(map(lambda x: name_map[x], r.keys()), r.values())) for r in rows]
</code></pre>
<p>Is this what you are after?</p>
| 2
|
2009-03-13T20:12:39Z
|
[
"python",
"dictionary"
] |
How do I re-map python dict keys
| 644,178
|
<p>I am working on a program that (among other things) reads a CSV file in (it gets stored as an array of dicts in the form <code>[{col1:data1a,col2:data2a},{col1:data1b,col2:data2b}]</code> ). For each row, as part of other processing, I need to remap those keys to user entered values, which are provided in another dict so they can be used as parameters in an API call. The mapping array is in the form: <code>{badname1:goodname1, badname2:goodname2,...}</code>.</p>
<p>So I'd like to get from:
<code>{badname1:data1, badname2:data2,...}</code> to <code>{goodname1:data1, goodname2:data2,...}</code></p>
<p>I'd like to use something like <code>zip()</code> (although <code>zip()</code> yields <code>{badname1:badname1,...}</code>).</p>
<p>Seems like there should be an obvious solution that is alluding me.</p>
<p>EDIT:
If the data is in <code>a</code> and the mapping in <code>b</code>:</p>
<p><code>dict(zip(b,a.itervalues()))</code></p>
<p>I get close, but it will only work in cases where the fields are known to be in the same order I think.</p>
| 11
|
2009-03-13T19:11:21Z
| 7,869,248
|
<p>If you are using Python 2.7 or Python 3.x, you can use a <a href="http://en.wikipedia.org/wiki/List_comprehension#Dict_comprehension" rel="nofollow">dictionary comprehension</a>. This is equivalent elo80ka's answer (which used a list comprehension), but produces slightly more readable code.</p>
<pre><code>name_map = {'oldcol1': 'newcol1', 'oldcol2': 'newcol2', 'oldcol3': 'newcol3'...}
for row in rows:
# Each row is a dict of the form: {'oldcol1': '...', 'oldcol2': '...'}
row = {name_map[name]: val for name, val in row.iteritems()}
...
</code></pre>
| 3
|
2011-10-23T21:12:41Z
|
[
"python",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.