Matthias Herrmann
Matthias Herrmann

Reputation: 2790

Python List Comprehension With Random Order

I'm creating a list in python and I need to randomize the items in the list.

Currently I have to use two lines for that:

  self.documents_news = [(brown.words(fileid), 'news') for fileid in brown.fileids('news')]
  random.shuffle(self.documents_news)

I want to have a oneliner and tried this:

self.documents_news = random.shuffle([(brown.words(fileid), 'news') for fileid in brown.fileids('news')])

But this is setting the value of self.documents_news to NoN.

How can I combine the random part with the creation of the list in one line and why is my approach resulting in a None value?

Upvotes: 2

Views: 770

Answers (2)

Cary Shindell
Cary Shindell

Reputation: 1386

I think you would be fine with just two lines. But random.shuffle is returning none because it shuffles in place. So you need to define a function shuffled:

def shuffled(l):
    random.shuffle(l)
    return l

documents_news = [(brown.words(fileid), 'news') for fileid in shuffled(brown.fileids('news'))]

Upvotes: 0

kichik
kichik

Reputation: 34704

random.shuffle() doesn't return the result, but shuffles in place. You can write a simple function that does both.

def shuffle_and_return(x):
  random.shuffle(x)
  return x

self.documents_news = shuffle_and_return([(brown.words(fileid), 'news') for fileid in brown.fileids('news')])

Upvotes: 4

Related Questions