Randomly select x number of items from class list

2019-02-17 03:42发布

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?

3条回答
Luminary・发光体
2楼-- · 2019-02-17 03:52

Remark - I renamed the list to lst. Assuming that you have a list of objects, try the following:

from random import randint
for item in lst[:randint(3, 20)]:
    (item.pid, item.aisle, item.bay, item.hits)
查看更多
对你真心纯属浪费
3楼-- · 2019-02-17 03:57
i = 0
while i < randint(3, 20):
    # Display code here.
    i += 1
查看更多
Anthone
4楼-- · 2019-02-17 04:09

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)
查看更多
登录 后发表回答