Issue
I'm trying to convert a list of list into a list of list with random values with some restrictions.
For example, I have the following list of lists.
a= [[10],[8],[4]] #this list will tell us how many elements/items should be in each list of list. For example in our new list, the first list will have 10 elements/items and so on.
b=[[15],[10],[5]] #this list will be used to determine the maximum number that each element can be. For example in our new list, since it can only have 10 elements/items we can only reach up to and including number 15. This process is done at random.
I need a new list a to look like the lists below. Each item in the list must be unique (so no repeating values is allowed)
new_list=[[1,2,4,5,8,9,10,11,12,13],[3,4,5,6,7,8,9,10],[1,2,4,5]] # sample output 1
new_list=[[5,6,7,8,9,10,11,12,13,14,15],[1,2,3,4,5,6,7,8],[2,3,4,5]] # sample output 2
This is what I have so far (MWE)
import random
a=[[10],[8],[4]] # list that informs the number of items in each list of list.
b=[[15],[10],[5]] # the restriction list.
new_list=[] #my final list
for values in a:
new_list.append(values[0])
new_list=[[item] for item in new_list]
print(new_list)
My problem is how do i convert the first list in my new_list into a random list using list b.
I hope this makes sense.
Solution
You can use a list comprehension with zip
:
new_list = [sorted(random.sample(range(1, j[0]+1), i[0])) for i,j in zip(a,b)]
Example output:
[[1, 2, 4, 7, 8, 10, 11, 12, 13, 14], [1, 3, 4, 5, 7, 8, 9, 10], [1, 2, 3, 4]]
Note that it would be easier to store your input as:
a = [10, 8, 4]
b = [15, 10, 5]
Then you wouldn't need to slice i
/j
with [0]
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.