Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly select x number of items from class list in python

In jython, I have a class of objects defined like this:

class Item:
  def __init__(self, pid, aisle, bay, hits, qtyPerOrder):
    self.pid = pid
    self.aisle = int(aisle)
    self.bay = bay
    self.hits = int(hits)
    self.qtyPerOrder = int(qtyPerOrder)

I have created a class list called "list" of the items in the class with 4000~ lines that look like this:

'PO78141', 13, ' B ', 40

I'm trying to randomly select a number within the range of 3 and 20 called x. Then, the code will select x number of lines in the list.

For example: if x = 5 I want it to return:

'PO78141', 13, ' B ', 40
'MA14338', 13, ' B ', 40
'GO05143', 13, ' C ', 40
'SE162004', 13, ' F ', 40
'WA15001', 13, ' F ', 40

EDIT Ok, that seems to work. However, it is returning this <main.Item object at 0x029990D0>. how do i get it to return it in the format above?

like image 237
user1683885 Avatar asked Sep 19 '12 19:09

user1683885


1 Answers

You can use the random module to both pick a number between 3 and 20, and to take a sample of lines:

import random

sample_size = random.randint(3, 20)
sample = random.sample(yourlist, sample_size)

for item in sample:
    print '%s, %d, %s, %d' % (item.pid, item.aisle, item.bay, item.hits)
like image 55
Martijn Pieters Avatar answered Nov 15 '22 04:11

Martijn Pieters