在Python中从班级列表中随机选择x个条目

7
在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)

我创建了一个名为“list”的类列表,其中包含4000多行的项,其中内容如下:

'PO78141', 13, ' B ', 40

我将尝试在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

编辑 好的,看起来它能正常工作。然而,它返回的是这个 <main.Item object at 0x029990D0>。我该如何让它以上述格式返回呢?


2
在Python中不要将任何东西命名为list,因为这会遮盖内置类型。 - Martijn Pieters
要从列表中选择N个随机元素,请使用random.sample:http://docs.python.org/library/random.html - georg
3个回答

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)

0

注意 - 我把列表重命名为lst。假设您有一个对象列表,请尝试以下操作:

from random import randint
for item in lst[:randint(3, 20)]:
    (item.pid, item.aisle, item.bay, item.hits)

你说“我希望它返回”到底是什么意思? - Firebowl2000

-1
i = 0
while i < randint(3, 20):
    # Display code here.
    i += 1

"randint" 不是一个序列。使用 "for i in randint(3, 20)" 会导致 "TypeError" 错误。 - Martijn Pieters
1
现在你将会在每次循环中测试i与一个新的随机值。这样也能得到正确的结果,但是你最好使用for i in xrange(randint(3, 20)): - Martijn Pieters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接