[Tutor] dealing with lists
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Feb 23 17:21:56 EST 2022
On 23/02/2022 20:11, marcus.luetolf at bluewin.ch wrote:
> I'd like to create 5 lists, each containing 4 sublists : f1, f2, f3, f4,
> f5, a total of 20 sublists.
That's not what your code below does. It only creates the 4 sublists.
But then it throws them away and creates another 4 and starts again.
> I have a list (named all_letters) contaning 16 characters a, b, c, ...p.
>
> I would liketo distribute all 16 characters to the 4 sublists 5 times in 5
> iterations respectivly so that as a condition a pair of characters,
> p.e. ['a', 'b', .] or ['a', 'c'.] or ['n', 'p' .] can appear only once
> in all 20 sublists.
You can probably use some of the python modules to do that
for you as a set of combinations or permutations or whatever
you actually want.
> To find the sublists fullfilling this condition I designed the following
> code with the intention to change the indices
> defined by the variables n and p til the condition is met :
>
>
>
> all_letters = list('abcdefghijklmnop')
>
> f1 = []
>
> f2 = []
>
> f3 = []
>
> f4 = []
Why not just define these at the top of the function
so you only have to do it once?
> n = 0
> p = 1
> for dummy_i in range(5):
> copy_all_letters = all_letters[:]
> lst = 16*copy_all_letters
>
> f1.append(lst[n+0])
> f1.append(lst[n+p])
> f1.append(lst[n+2*p])
> f1.append(lst[n+3*p])
> f1.sort()
You could do that all in one line:
f1 = sorted([ lst[n],lst[n+p],lst[n+2*p], lst[n+3*p] ])
...
> f2.sort()
>
...
> f3.sort()
...> f4.sort()
> print('f1: ', f1)
> print('f2: ', f2)
> print('f3: ', f3)
> print('f4: ', f4)
>
> n += 4
> p += 1
>
> f1 = []
>
> f2 = []
>
> f3 = []
>
> f4 = []
>
> f5 = []
Where did f5 come from? You only build 4 lists?
And you've now thrown them away and are staring
from scratch with new indices.
> But I'm unable to define the condition mentioned
> above and asking for your help.
I don't understand that comment. Can you be more
specific about what you expect and what you get?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list