Re: newbie list processing question

Daniel Ashbrook <[email protected]>
Newsgroups gmane.comp.python.pyrex,gmane.comp.python.cython.devel
Message-ID <[email protected]>
Robert Bradshaw wrote:
>> def addOne(l):
>>    return [i+1 for i in l]
 >> ...
> 
> This last implementation of addOne should work as is in Cython, and will 
> be nearly optimal (assuming your CPU has reasonable branch prediction). 
> However, if you are manipulating word-sized integers, using C arrays 
> will give you a manyfold over python arithmetic.

So in the real code, I'm actually doing float math. And I'll be wanting 
to return my results in a list object. There will be many thousands of 
float results; what's the best way to deal with that? Use a C-specific 
data structure to store the results then turn it into a list somehow?

> Did you do
> 
> cdef int i
> for i from 0 <= i < len(L):
>     ...

Ah, I missed the "cdef int i" part of it.

> In Cython, if one writes
> 
> L[i]
> 
> where i is a cdef int, then it checks to see at runtime if L is a list 
> and accesses its elements via a macro. Otherwise one can use 
> PyList_SetItem and friends, but as you have noticed that is cumbersome 
> (as well ahs being hard to read).

Oh ho! That works very nicely; I'll include code to help others in the 
future:

   cdef int i
   for i from 0 <= i < len(l):
     l[i] = l[i] + 1


Thanks for the help!


dan
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.