how to iterate over sequence and non-sequence ?
paul.hankin at gmail.com
Fri Oct 19 09:33:42 CEST 2007
On Oct 19, 12:24 am, stef mientki <stef.mien... at gmail.com> wrote:
> I generate dynamically a sequence of values,
> but this "sequence" could also have length 1 or even length 0.
> So I get some line in the form of:
> line = '(2,3,4)'
> line = ''
> line = '(2)'
> (in fact these are not constant numbers, but all kind of integer
> variables, coming from all over the program, selected from a tree, that
> shows all "reachable" variables)
> So in fact I get the value from an exec statement, like this
> exec 'signals = ' + line
> Now I want to iterate over "signals", which works perfect if there are 2
> or more signals,
> but it fails when I have none or just 1 signal.
> for value in signals :
> do something
> As this meant for real-time signals, I want it fast, so (I think) I
> can't afford extensive testing.
> Any smart solution there ?
First: don't collect data into strings - python has many container
types which you can use.
Next, your strings look like they're supposed to contain tuples. In
fact, tuples are a bit awkward sometimes because you have to use
'(a,') for a tuple with one element - (2) isn't a tuple of length one,
it's the same as 2. Either cope with this special case, or use lists.
Either way, you'll have to use () or  for an empty sequence.
More information about the Python-list