从python中的类列表中随机选择x个项目

use*_*885 7 python random jython class list

在jython中,我有一类像这样定义的对象:

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)
Run Code Online (Sandbox Code Playgroud)

我创建了一个名为"list"的类列表,该类列表中的项目有4000~行,如下所示:

'PO78141', 13, ' B ', 40
Run Code Online (Sandbox Code Playgroud)

我试图随机选择一个范围为3和20的数字,称为x.然后,代码将在列表中选择x行.

例如:如果x = 5,我希望它返回:

'PO78141', 13, ' B ', 40
'MA14338', 13, ' B ', 40
'GO05143', 13, ' C ', 40
'SE162004', 13, ' F ', 40
'WA15001', 13, ' F ', 40
Run Code Online (Sandbox Code Playgroud)

编辑 好吧,这似乎工作.但是,它将返回此< main .Item对象0x029990D0>.我如何让它以上述格式返回?

Mar*_*ers 12

您可以使用该random模块选择3到20之间的数字,并采取行样本:

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)
Run Code Online (Sandbox Code Playgroud)


BSu*_*ull -1

i = 0
while i < randint(3, 20):
    # Display code here.
    i += 1
Run Code Online (Sandbox Code Playgroud)