[exec cmd for cmd in cmds]

  • Thread starter =?ISO-8859-1?Q?Sch=FCle_Daniel?=
  • Start date
?

=?ISO-8859-1?Q?Sch=FCle_Daniel?=

Hello all,
>>> p = "z%i = complex(1-1e-%i, 1-1e-%i)"
>>> lst = [p % (i,i,i) for i in range(10, 30)]
>>> for item in lst:
.... exec item
....
>>>
>>> p = "z%i = complex(1-1e-%i, 1-1e-%i)"
>>> lst = [p % (i,i,i) for i in range(10, 30)]
>>> [exec item for item in lst]
File "<stdin>", line 1
[exec item for item in lst]
^
SyntaxError: invalid syntax
is this prohibited for some reasons or is this just happens to be
disallowed?


this is one more cool way
>>> p = "z%i = complex(1-1e-%i, 1-1e-%i);"
>>> c = reduce(lambda x,y: x+y, [p % (i,i,i) for i in range(20,30)])
>>> exec c

and one more :)
>>> p = "z%i = complex(1-1e-%i, 1-1e-%i);"
>>> c = "".join([ p % (i,i,i) for i in range(20,30) ])
>>> exec c

Regards, Daniel
 
D

Diez B. Roggisch

Schüle Daniel said:
Hello all,
p = "z%i = complex(1-1e-%i, 1-1e-%i)"
lst = [p % (i,i,i) for i in range(10, 30)]
for item in lst:
... exec item
...
p = "z%i = complex(1-1e-%i, 1-1e-%i)"
lst = [p % (i,i,i) for i in range(10, 30)]
[exec item for item in lst]
File "<stdin>", line 1
[exec item for item in lst]
^
SyntaxError: invalid syntax
is this prohibited for some reasons or is this just happens to be
disallowed?

exec is a statement. And statements aren' allowed in the _expression_ of a
list-comprehension.
this is one more cool way
p = "z%i = complex(1-1e-%i, 1-1e-%i);"
c = reduce(lambda x,y: x+y, [p % (i,i,i) for i in range(20,30)])
exec c

and one more :)
p = "z%i = complex(1-1e-%i, 1-1e-%i);"
c = "".join([ p % (i,i,i) for i in range(20,30) ])
exec c

If you think so :) Ususally people go for dictionaries in such cases.

Diez
 
S

Scott David Daniels

Schüle Daniel said:
you are right, I didn't think about dictionaries
p = "complex(1-1e-%i, 1-1e-%i)"
d={}
[d.update({i:eval(p % (i,i))}) for i in range(20,30)]
[None, None, None, None, None, None, None, None, None, None]

so now the work is complete :)

Regards
Really, isn't this clearer?:

d = {}
for i in range(20, 30):
v = 1. - 10. ** -i
d = complex(v, v)

If you must repair the mess above, try:

p = "complex(1-1e-%i, 1-1e-%i)"
d = dict([(i, eval(p % (i, i))) for i in range(20, 30)])

Strive to be clear first, terse second given the first is still
achieved.

--Scott David Daniels
(e-mail address removed)
 

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
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top