DJM
DJM

Reputation: 81

Populating a list of lists with random items

I have a list of lists with a certain range:

l = [["this", "is", "a"], ["list", "of"], ["lists", "that", "i", "want"], ["to", "copy"]]

And a list of words:

words = ["lorem", "ipsum", "dolor", "sit", "amet", "id", "sint", "risus", "per", "ut", "enim", "velit", "nunc", "ultricies"]

I need to create an exact replica of the list of lists, but with random terms picked from the other list.

This was the first thing that came to mind, but no dice.

for random.choice in words:
  for x in list:
    for y in x:
      y = random.choice

Any ideas? Thank you in advance!

Upvotes: 1

Views: 358

Answers (3)

Mike Müller
Mike Müller

Reputation: 85442

You can use list comprehensions for this:

import random
my_list = [[1, 2, 3], [5, 6]]
words = ['hello', 'Python']

new_list = [[random.choice(words) for y in x] for x in my_list]
print(new_list)

Output:

[['Python', 'Python', 'hello'], ['Python', 'hello']]

This is equivalent to:

new_list = []
for x in my_list:
    subl = []
    for y in x:
        subl.append(random.choice(words))
    new_list.append(subl)

With your example data:

my_list = [['this', 'is', 'a'], ['list', 'of'], 
           ['lists', 'that', 'i', 'want'], ['to', 'copy']]

words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'id', 'sint', 'risus',
         'per', 'ut', 'enim', 'velit', 'nunc', 'ultricies']
new_list = [[random.choice(words) for y in x] for x in my_list]
print(new_list)

Output:

[['enim', 'risus', 'sint'], ['dolor', 'lorem'], ['sint', 'nunc', 'ut', 'lorem'], ['ipsum', 'amet']]

Upvotes: 4

keredson
keredson

Reputation: 3088

You should flatten your list of lists, then shuffle, then rebuild. Example:

import random

def super_shuffle(lol):
  sublist_lengths = [len(sublist) for sublist in lol]
  flat = [item for sublist in lol for item in sublist]
  random.shuffle(flat)
  pos = 0
  shuffled_lol = []
  for length in sublist_lengths:
    shuffled_lol.append(flat[pos:pos+length])
    pos += length
  return shuffled_lol

print super_shuffle([[1,2,3,4],[5,6,7],[8,9]])

Prints:

[[7, 8, 5, 6], [9, 1, 3], [2, 4]]

This randomizes across ALL the lists, not just within a single sublist and guarantees no dups.

Upvotes: 1

Ben Stobbs
Ben Stobbs

Reputation: 434

You're not storing the values back into your lists. Try:

for i in range(0, len(list)):
    subl = list[i]
    for n in range(0, len(subl)):
        list[i][n] = random.choice(words)

Upvotes: 1

Related Questions