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

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

本文介绍了从python的类列表中随机选择x个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

我创建了一个名为"list"的类列表,该类列表包含4000条如下所示的行:

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

我正在尝试随机选择一个介于3到20之间的数字,称为x.然后,代码将选择列表中x的行数.

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.

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

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

编辑好的,那似乎行得通.但是,它将在0x029990D0>返回此< 主要 .Item对象.我如何以上面的格式返回它?

EDITOk, 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?

推荐答案

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

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)

这篇关于从python的类列表中随机选择x个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:39