Simple list question

C

C GIllespie

Dear all,

I have a list something like this: ['1','+','2'], I went to go through and
change the numbers to floats, e.g. [1,'+',2]. What's the best way of doing
this? The way I done it seems wrong, e.g.

nod=['1','+','2']
i=0
while i<len(nod):
if nod !='+' or nod !='-' or nod!='*' or nod != '/' or
nod != '(' or nod != ')':
nod = float(nod)
i = i + 1

Comments?

Thanks

Colin
 
D

Dave Brueck

C said:
I have a list something like this: ['1','+','2'], I went to go through and
change the numbers to floats, e.g. [1,'+',2]. What's the best way of doing
this? The way I done it seems wrong, e.g.

nod=['1','+','2']
i=0
while i<len(nod):
if nod !='+' or nod !='-' or nod!='*' or nod != '/' or
nod != '(' or nod != ')':
nod = float(nod)
i = i + 1


How about:
nod = ['1','+','2']
for i in range(len(nod)):
.... try:
.... nod = float(nod)
.... except ValueError: pass
....[1.0, '+', 2.0]

-Dave
 
P

Peter Otten

C said:
Dear all,

I have a list something like this: ['1','+','2'], I went to go through and
change the numbers to floats, e.g. [1,'+',2]. What's the best way of doing

If you really want the [1,'+',2] format, use int() instead of float().
this? The way I done it seems wrong, e.g.

nod=['1','+','2']
i=0
while i<len(nod):
if nod !='+' or nod !='-' or nod!='*' or nod != '/' or
nod != '(' or nod != ')':
nod = float(nod)
i = i + 1

Comments?


Nothing is wrong with the above, although a for loop is more common.

for i in range(len(nod)):
# ...

Instead of testing for all non-floats, you could just try to convert the
list item, keeping it unchanged if an error occurs. Here's a full example
using enumerate() instead of range():
nod = ["1", "+", "2"]
for i, v in enumerate(nod):
.... try:
.... v = float(v)
.... except ValueError:
.... pass
.... else: # yes, try...except has an else (=no exception) branch, too
.... nod = v
....[1.0, '+', 2.0]

Peter
 
S

Stefan Axelsson

How about:
nod = ['1','+','2']
for i in range(len(nod)):
... try:
... nod = float(nod)
... except ValueError: pass
...[1.0, '+', 2.0]


Perhaps minor style issue; I'd use 'map' (even though Guido isn't
crazy about it), or perhaps a list comprehension.

Like so:
.... try:
.... return float(x)
.... except ValueError: return x
....
[1.0, '+', 2.0]

Stefan,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,501
Latest member
Ledmyplace

Latest Threads

Top