473,574 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Making things more functional in Python

Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors

Namely, I'd like to get rid of the initilization
(vectors = {}) and also the loop Yet, I'd hate to put
an assignment into Python's FP list comprehensions.

Ideally, I'd like something like this:
vectors.dict_ad d({d:result}) for [sample.get_val( d)
for sample in samples for d in dset].

Is there anything like that? Am I missing the
picture?

Thanks.

PS If possible, please cc me on all responses, thanks.


_______________ _______________ ____
Celebrate Yahoo!'s 10th Birthday!
Yahoo! Netrospective: 100 Moments of the Web
http://birthday.yahoo.com/netrospective/
Jul 18 '05 #1
6 1252
gf gf wrote:
Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors

Namely, I'd like to get rid of the initilization
(vectors = {}) and also the loop
Generate the whole dictionary on the fly with a Python 2.4 generator
expression:

dict((d, [sample.get_val( d) for sample in samples]) for d in dset)

Whether this is "better" or not I think mainly hinges on which
one you ahve an easier time understanding later. Personally I would
prefer this version, but it's easy to get carried away trying to
functionalize things to the point that a procedural version is much
easier to understand.
Yet, I'd hate to put an assignment into Python's FP list
comprehensions.
Indeed it's not possible to have an assignment in a list comprehension.
(Unless it's a side-effect due to a function called by the list
comprehension.)
Ideally, I'd like something like this:
vectors.dict_ad d({d:result}) for [sample.get_val( d)
for sample in samples for d in dset].


You can't use the name "vectors" without first initializing it
somehow!
--
Michael Hoffman
Jul 18 '05 #2
gf gf wrote:
Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors

Namely, I'd like to get rid of the initilization
(vectors = {}) and also the loop Yet, I'd hate to put
an assignment into Python's FP list comprehensions.

Ideally, I'd like something like this:
vectors.dict_ad d({d:result}) for [sample.get_val( d)
for sample in samples for d in dset].

Is there anything like that? Am I missing the
picture?

Thanks.

PS If possible, please cc me on all responses, thanks.

The logical thing to use would be

return dict([(d, sample.getval(d )) for d in dset for sample in samples])

which (I think) should work from 2.2 onwards.

regards
Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #3
Steve Holden wrote:
return dict([(d, sample.getval(d )) for d in dset for sample in samples])


That won't do what the original code does. This sets dict[d] to
samples[-1].getval(d) instead of [sample.getval(d ) for sample in samples].
--
Michael Hoffman
Jul 18 '05 #4
Michael Hoffman wrote:
Steve Holden wrote:
return dict([(d, sample.getval(d )) for d in dset for sample in samples])

That won't do what the original code does. This sets dict[d] to
samples[-1].getval(d) instead of [sample.getval(d ) for sample in samples].


My bad, I didn;t look closely enbough to see the need for the nested
comprehensions.

regards
Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #5
On Fri, 2005-03-04 at 08:36 -0800, gf gf wrote:
Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors


You could use reduce:

def compute_vectors (samples, dset):
def add_entry(vecto rs, d):
vectors[d] = [sample.get_val( d) for sample in samples]
return vectors
return reduce(add_entr y, dset, {})

Dave
Jul 18 '05 #6
On Sat, 2005-03-05 at 00:00 -0700, Dave Benjamin wrote:
On Fri, 2005-03-04 at 08:36 -0800, gf gf wrote:
Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors


You could use reduce:

def compute_vectors (samples, dset):
def add_entry(vecto rs, d):
vectors[d] = [sample.get_val( d) for sample in samples]
return vectors
return reduce(add_entr y, dset, {})


This could be further generalized:

def compute(xs, ys, f):
def add_entry(resul t, y):
result[y] = [f(x, y) for x in xs]
return result
return reduce(add_entr y, ys, {})

Now, compute_vectors is just:

compute(samples , dset, lambda x, y: x.get_val(y))

You could even abstract the method call:

def method(name):
def _method(obj, *args, **kwds):
return getattr(obj, name)(*args, **kwds)
return _method

compute(samples , dset, method('get_val '))

Dave
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
3421
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then I've also heard there are lots of weird ways to do some things kinda like Perl which is bad for me. Any other ideas?
12
1655
by: Ryan Paul | last post by:
I've spent a lot of time using python, and personally, I feel like it is vastly superior when compared to languages like java, and c++, but there are still a few things that detract from its elegance and flexibility. I thought I might mention a few of them. I'd like to hear what people think of my complaints, and I also like to hear the...
8
1558
by: beza1e1 | last post by:
I see myself shifting more and more over to the functional kind of coding. Could be related to the Haskell, we had to learn in CS. Now i was wondering, how other people use Python? With functional i mean my files mostly consist of functions and only rarely i use "class". The library modules seem to be mostly written the object-way on the...
0
2252
by: Xah Lee | last post by:
One-Liner Loop in Functional Style Xah Lee, 200510 Today we show a example of a loop done as a one-liner of Functional Programing style. Suppose you have a list of file full paths of images: /Users/t/t4/oh/DSCN2059m-s.jpg
17
1971
by: ToddLMorgan | last post by:
I'm just starting out with python, after having a long history with Java. I was wondering if there were any resources or tips from anyone out there in Python-land that can help me make the transition as successfully as possible? Perhaps you've made the transition yourself or just have experience with folks who have made the transition. I'm...
15
1711
by: Lorenzo Stella | last post by:
Hi all, I haven't experienced functional programming very much, but now I'm trying to learn Haskell and I've learned that: 1) in functional programming LISTS are fundmental; 2) any "cycle" in FP become recursion. I also know that Python got some useful tool such as map, filter, reduce... so I told: "let's try some FP-style programming with...
16
2382
by: Andrea Gavana | last post by:
Hi Diez & All, Do you mind explaining "why" you find it *buttugly*? I am asking just out of curiosity, obviously. I am so biased towards wxPython that I won't make any comment on this thread in particular, but I am curious to know why some people find it "ugly" or "bad" or whatever. It has its own bugs and missing features, of course, but...
10
977
by: James Fassett | last post by:
Hi all, Had a simple problem that turned into an interesting solution and I thought I would share it here. I had a list of tuples that I needed to get the first value from and generate a list. tuple_list = ( ('John', 'Doe'),
50
4445
by: Juha Nieminen | last post by:
I asked a long time ago in this group how to make a smart pointer which works with incomplete types. I got this answer (only relevant parts included): //------------------------------------------------------------------ template<typename Data_t> class SmartPointer { Data_t* data; void(*deleterFunc)(Data_t*);
0
7797
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7715
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8041
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8225
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7806
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8093
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5296
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3748
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2233
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.