[Tutor] a list of tuples with varying lengths

Roel Schroeven roel at roelschroeven.net
Wed Jan 19 03:45:44 EST 2022


Op 19/01/2022 om 7:20 schreef Phil:
> I hope the following makes sense to you and I'm not sure that I should 
> even post such a vague question.
>
> What I need is s, d to = (0, 4) during the first time interval and 
> then s, d = (0, 3) and (1, 4) the second time. There are many time 
> intervals, this is just the first two.
>
> My solution is to have a look_up table that looks something like this, 
> the first three entries are:
>
> table = [[(0, 4)], [(0, 3), (1, 4)], [(0, 2), (1, 3), (2, 4)]]
>
> The first entry has 1 tuple the second entry has 2 tuples the third 
> has 3 tuples, etc
>
> My first thought was to extract the tuple values with a for-loop with 
> a variable range, like this: for s, d in range(len(table[index])) but 
> that idea ended in failure. I cannot see a simple way to calculate the 
> values even though there is a pattern and so a look-up table seems 
> like a good idea.
>
> I've spent days on this and have made little progress so any ideas 
> will be greatly appreciated.

Something like this?

lookup_table = [[(0, 4)], [(0, 3), (1, 4)], [(0, 2), (1, 3), (2, 4)]]

for time_interval in lookup_table:
     print('{} tuple(s) in this time interval:'.format(len(time_interval)))
     for s, d in time_interval:
         print('    {}, {}'.format(s, d))

That outputs this:

1 tuple(s) in this time interval:
     0, 4
2 tuple(s) in this time interval:
     0, 3
     1, 4
3 tuple(s) in this time interval:
     0, 2
     1, 3
     2, 4

In cases where you don't only need each element but also want a loop 
index, use enumerate():

lookup_table = [[(0, 4)], [(0, 3), (1, 4)], [(0, 2), (1, 3), (2, 4)]]

for time_interval_index, time_interval in enumerate(lookup_table):
     print('{} tuple(s) in time interval {}:'.format(len(time_interval), 
time_interval_index))
     for i, (s, d) in enumerate(time_interval):
         print('    {}: {}, {}'.format(i, s, d))

This variation outputs:

1 tuple(s) in time interval 0:
     0: 0, 4
2 tuple(s) in time interval 1:
     0: 0, 3
     1: 1, 4
3 tuple(s) in time interval 2:
     0: 0, 2
     1: 1, 3
     2: 2, 4


-- 
"Je ne suis pas d’accord avec ce que vous dites, mais je me battrai jusqu’à
la mort pour que vous ayez le droit de le dire."
         -- Attribué à Voltaire
"I disapprove of what you say, but I will defend to the death your right to
say it."
         -- Attributed to Voltaire
"Ik ben het niet eens met wat je zegt, maar ik zal je recht om het te zeggen
tot de dood toe verdedigen"
         -- Toegeschreven aan Voltaire



More information about the Tutor mailing list