473,289 Members | 1,866 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

Better writing in python

I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...

Oct 24 '07 #1
19 1836
On Wed, 24 Oct 2007 12:09:40 +0000, Alexandre Badez wrote:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
Drop the prefixes. `l` is for list? `d` is for what!? Can't be
dictionary because the code doesn't make much sense.

Where is `cls` coming from?

Ciao,
Marc 'BlackJack' Rintsch
Oct 24 '07 #2
On Oct 24, 1:09 pm, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
import operator
return filter(cls.dArguments), filter(operator.not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

Oct 24 '07 #3
On Oct 24, 1:09 pm, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
import operator
return filter(cls.dArguments), filter(operator.not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

Oct 24 '07 #4
On Oct 24, 1:09 pm, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
import operator
return filter(cls.dArguments), filter(operator.not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

Oct 24 '07 #5
On Oct 24, 7:09 am, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
You might look into list comprehensions. You could probably do this
with two of them:

<code>
# completely untested
lMandatory = [arg for arg in cls.dArguments if arg is True]
lOptional = [arg for arg in cls.dArguments if arg is False]
</code>

Something like that. I'm not the best with list comprehensions, so I
may have the syntax just slightly off. See the following links for
more information:

http://www.secnetix.de/olli/Python/l...ehensions.hawk
http://docs.python.org/tut/node7.html

Mike

Oct 24 '07 #6
On 2007-10-24, Alexandre Badez <al*************@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this
code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
I don't think there's much improvement to be made. What are your
particular concerns? Is it too slow? Too verbose? Does it not
work correctly?

It appears to be an application of itertools.groupby, but that'll
almost certainly be less efficient. To use groupby, you have to
sort by your predicate, and build lists to save results. Your for
loop avoids the sorting.

Here's some instrumentality for ya:

from itertools import groupby
from operator import truth
from collections import defaultdict

result = defaultdict(list)
for k, g in groupby(sorted(cls.dArguments, key=truth), truth):
result[k].extend(g)

I like your initial attempt better.

P.S. I didn't realize until working out this example that extend
could consume an iterator.

--
Neil Cerutti
The word "genius" isn't applicable in football. A genius is a guy like Norman
Einstein. --Joe Theisman
Oct 24 '07 #7
Hi Alexandre,

On Oct 24, 2:09 pm, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this code
Please tell us, what it is you want to achieve. And give us some
context
for this function.
lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)
This snippet will seperate d.Arguments into two lists: one that
holds all elements that are references to True(!) and another list
that holds the rest. The condition 'if args is True' will only
be hold if arg actually _is_ the object _True_. This is probably
not what you want. Apart from that, you might go with

lMandatory = [ arg for arg in cls.dArguments if condition() ]
lOptional = [ arg for arg in cls.dArguments if not condition() ]

the second line could be rewritten

lOptional = list(set(cls.dArguments)-set(lMandatory))

If lMandatory and lOptional do not need to be lists, you can also
write

lMandatory = set(arg for arg in cls.dArguments if condition())
lOptional = set(cls.dArguments) - lMandatory

But please, give us some more context of what you want to do.

- harold -

Oct 24 '07 #8
Thanks for your try Cliff, I was very confused :P
More over I made some mistake when I post (to make it easiest).

Here is my real code:

with
dArguments = {
'argName' : {
'mandatory' : bool, # True or False
[...], # other field we do not care here
}
}

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if cls.dArguments[arg]['mandatory']:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

So, as you see, we agree each other about "if bool" or "if bool is
True" ;)

So, my question was how to give it a better 'python like' look ?
Any idea ?

Oct 24 '07 #9
Alexandre Badez <al*************@gmail.comwrote:
Thanks for your try Cliff, I was very confused :P
More over I made some mistake when I post (to make it easiest).

Here is my real code:

with
dArguments = {
'argName' : {
'mandatory' : bool, # True or False
[...], # other field we do not care here
}
}

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if cls.dArguments[arg]['mandatory']:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

So, as you see, we agree each other about "if bool" or "if bool is
True" ;)

So, my question was how to give it a better 'python like' look ?
Any idea ?

For a 'python like' look lose the Hungarian notation (even Microsoft
have largely stopped using it), increase the indentation to 4 spaces,
and also get rid of the spurious parentheses around the result.
Otherwise it is fine: clear and to the point.

If you really wanted you could write something like:

m, o = [], []
for arg in cls.dArguments:
(m if cls.dArguments[arg]['mandatory'] else o).append(arg)
return m, o

Or even:
m, o = [], []
action = [o.append, m.append]
for arg in cls.dArguments:
action[bool(cls.dArguments[arg]['mandatory'])](arg)
return m, o

but it just makes the code less clear, so why bother?
Oct 24 '07 #10
On Oct 24, 8:02 am, kyoso...@gmail.com wrote:
On Oct 24, 7:09 am, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this code
lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)
I think there is a better way, but I can't see how...

You might look into list comprehensions. You could probably do this
with two of them:

<code>
# completely untested
lMandatory = [arg for arg in cls.dArguments if arg is True]
lOptional = [arg for arg in cls.dArguments if arg is False]
</code>

Something like that. I'm not the best with list comprehensions, so I
may have the syntax just slightly off. See the following links for
more information:

http://www.secnetix.de/olli/Python/l...tut/node7.html

Mike
After reading the others replies, it makes me think that I'm barking
up the wrong tree. Ah well.

Mike

Oct 24 '07 #11
On 2007-10-24, Alexandre Badez <al*************@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this
code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
You can do it shorter, not sure that it also qualifies as better....

d = { True : [] , False : [] }
for arg in cls.arguments:
d[arg == True].append(arg)

return d[True], d[False]

One potential problem here is that 'arg == True' may not be the same as 'if
arg:'. I couldn't come up with a better equivalent expression, maybe one of the
other readers knows more about this?
Albert

Oct 24 '07 #12
Alexandre Badez wrote:
I'm just wondering, if I could write a in a "better" way this code
[...]
I think there is a better way, but I can't see how...
What's "better" for you? Shorter? More performant? More readable?
Complying with best practice? Closely following a specific
programming paradigm?

Regards,
Björn

--
BOFH excuse #403:

Sysadmin didn't hear pager go off due to loud music from bar-room
speakers.

Oct 24 '07 #13
On Oct 24, 2:02 pm, kyoso...@gmail.com wrote:
On Oct 24, 7:09 am, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this code
lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)
I think there is a better way, but I can't see how...

You might look into list comprehensions. You could probably do this
with two of them:

<code>
# completely untested
lMandatory = [arg for arg in cls.dArguments if arg is True]
lOptional = [arg for arg in cls.dArguments if arg is False]
</code>

Something like that. I'm not the best with list comprehensions, so I
may have the syntax just slightly off.
Your list comprehensions are right, but 'arg is True' and 'arg is
False' are better written as 'arg' and 'not arg' respectively.

--
Paul Hankin

Oct 24 '07 #14
On Oct 24, 4:15 pm, Paul Hankin <paul.han...@gmail.comwrote:
On Oct 24, 2:02 pm, kyoso...@gmail.com wrote:
On Oct 24, 7:09 am, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this code
lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)
I think there is a better way, but I can't see how...
You might look into list comprehensions. You could probably do this
with two of them:
<code>
# completely untested
lMandatory = [arg for arg in cls.dArguments if arg is True]
lOptional = [arg for arg in cls.dArguments if arg is False]
</code>
Something like that. I'm not the best with list comprehensions, so I
may have the syntax just slightly off.

Your list comprehensions are right, but 'arg is True' and 'arg is
False' are better written as 'arg' and 'not arg' respectively.

--
Paul Hankin
Anyone know why towards arg is True and arg is False, arg is None is
faster than arg == None ...

Oct 24 '07 #15
On Oct 24, 10:42 am, cokofree...@gmail.com wrote:
On Oct 24, 4:15 pm, Paul Hankin <paul.han...@gmail.comwrote:
On Oct 24, 2:02 pm, kyoso...@gmail.com wrote:
On Oct 24, 7:09 am, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this code
lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)
I think there is a better way, but I can't see how...
You might look into list comprehensions. You could probably do this
with two of them:
<code>
# completely untested
lMandatory = [arg for arg in cls.dArguments if arg is True]
lOptional = [arg for arg in cls.dArguments if arg is False]
</code>
Something like that. I'm not the best with list comprehensions, so I
may have the syntax just slightly off.
Your list comprehensions are right, but 'arg is True' and 'arg is
False' are better written as 'arg' and 'not arg' respectively.
--
Paul Hankin

Anyone know why towards arg is True and arg is False, arg is None is
faster than arg == None ...
And quite often incorrect, especially the "arg is True" and "arg is
False".

Oct 24 '07 #16
On Wed, 24 Oct 2007 16:04:28 +0200, A.T.Hofkamp wrote:
>On 2007-10-24, Alexandre Badez <al*************@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this
code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...

You can do it shorter, not sure that it also qualifies as better....

d = { True : [] , False : [] }
for arg in cls.arguments:
d[arg == True].append(arg)

return d[True], d[False]

One potential problem here is that 'arg == True' may not be the same as 'if
arg:'. I couldn't come up with a better equivalent expression, maybe one of the
other readers knows more about this?
With ``if arg:`` the interpreter asks `arg` for its "boolean value". So a
better way would be:

d[bool(arg)].append(arg)

As `True` and `False` are instances of `int` with the values 1 and 0 it's
possible to replace the dictionary by a list:

tmp = [[], []]
for arg in cls.arguments:
tmp[bool(arg)].append(arg)
return tmp[1], tmp[0]

Maybe that's nicer. Maybe not.

Ciao,
Marc 'BlackJack' Rintsch
Oct 24 '07 #17
Bjoern Schliessmann a écrit :
Alexandre Badez wrote:
>I'm just wondering, if I could write a in a "better" way this code
[...]
I think there is a better way, but I can't see how...

What's "better" for you? Shorter? More performant? More readable?
Complying with best practice? Closely following a specific
programming paradigm?
I think the OP meant "more pythonic".

Oct 24 '07 #18
On Oct 24, 9:04 am, "A.T.Hofkamp" <h...@se-162.se.wtb.tue.nlwrote:
On 2007-10-24, Alexandre Badez <alexandre.ba...@gmail.comwrote:
I'm just wondering, if I could write a in a "better" way this
code
lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)
I think there is a better way, but I can't see how...

You can do it shorter, not sure that it also qualifies as better....

d = { True : [] , False : [] }
for arg in cls.arguments:
d[arg == True].append(arg)

return d[True], d[False]

One potential problem here is that 'arg == True' may not be the same as 'if
arg:'. I couldn't come up with a better equivalent expression, maybe one of the
other readers knows more about this?

Albert
d[bool(arg)].append(arg) resolves your concern?

Oct 24 '07 #19
On Oct 24, 3:46 pm, Duncan Booth <duncan.bo...@invalid.invalidwrote:
For a 'python like' look lose the Hungarian notation (even Microsoft
have largely stopped using it)
I wish I could.
But my corporation do not want to apply python.org coding rules
increase the indentation to 4 spaces,
Well, it is in my python file.
I do not do it here, because I'm a bit lazy.
and also get rid of the spurious parentheses around the result.
Thanks
Otherwise it is fine: clear and to the point.
Thanks
>
If you really wanted you could write something like:

m, o = [], []
for arg in cls.dArguments:
(m if cls.dArguments[arg]['mandatory'] else o).append(arg)
return m, o

Or even:
m, o = [], []
action = [o.append, m.append]
for arg in cls.dArguments:
action[bool(cls.dArguments[arg]['mandatory'])](arg)
return m, o

but it just makes the code less clear, so why bother?
And finally thanks again ;)

Oct 24 '07 #20

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

Similar topics

6
by: Bengt Richter | last post by:
>>> hex(-5) __main__:1: FutureWarning: hex()/oct() of negative int will return a signed string in Python 2.4 and up '0xfffffffb' >>> hex(-5) '0xfffffffb' >>> hex(-5L) '-0x5L' That is sooo...
220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
6
by: Michael | last post by:
Hi, I'm fairly new at Python, and have the following code that works but isn't very concise, is there a better way of writing it?? It seems much more lengthy than python code i have read..... :-)...
2
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to...
6
by: Dan Jacobson | last post by:
Can I feel even better about using perl vs. python, as apparently python's dependence of formatting, indentation, etc. vs. perl's "(){};" etc. makes writing python programs perhaps very device...
6
by: Anton Vredegoor | last post by:
Since a few days I've been experimenting with a construct that enables me to send the sourcecode of the web page I'm reading through a Python script and then into a new tab in Mozilla. The new tab...
7
by: apollonius2 | last post by:
Greetings, I have been working on a little project today to help me better understand classes in Python (I really like Python). I am a self taught programmer and consider myself to fall in the...
3
by: koutoo | last post by:
I have a code that writes to 2 seperate files. I keep getting a "list index out of range" error. The strange part is that when checking the files that I'm writing too, the script has already...
13
by: Marco Bizzarri | last post by:
Sorry... pressed enter but really didn't want to. As I said, let's say I have a class class A: def __init__(self): self.x = None
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.