Maybe a list comprehsnion is not the right way to go here.

I want to define a nested list that a user can tell how many lists and how many entries in each subllist. Then have random call a value for each entry in the sublist, working on unique entries for each sublist(but can get round to that later

So I created a basic test case

import random


d = (1, 2, 3, 4, 5, 6, 7, 8, 9)
userVal1 = 3
userVal2 = 4
arand = random.choice(d)

x = [[arand for i in range(userVal1)] for j in range(userVal2)]
print x

Now it creates a list of 3 entries 4 times so that works.

sayth@linux-g8u9:~/dev/multi> python3 test_loop.py
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]

But it only pulls the first random number and populates it across the list, I want it to repick for each entry.

NB I have a better random system I am working on so that function arand is just for testing in this case.
for some reason I really cannot get my head around list comprehsenions and/or looping to create multiple lists.

Edit: I have tried a list comprehension, it is not necessary that this would need to be the solution.

You must use function inside list comprehension:

import random


d = (1, 2, 3, 4, 5, 6, 7, 8, 9)
userVal1 = 3
userVal2 = 4


x = [[random.choice(d) for i in range(userVal1)] for j in range(userVal2)]
print x

""" Output:
[[2, 4, 7], [6, 8, 2], [2, 7, 2], [6, 7, 3]]
"""
Member Avatar for Warrens80

Uh? What r u guys talking about

So if I then want to introduce logic to keep the entries of each sublist unique

eg from the example out posted above the 3rd sublist has [2, 7, 2], so I want to eliminate 2 from occuring twice.

I should pull this out to a for loop?

No, then you should use random sample instead of inner list comprehension.

Thanks pytony but I can't use sample because I am implanted weighted random.

Then you call your own random sample function/generator (using a set of used value's indexes to not repeat values)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.