【问题标题】:Randomly select x number of items from class list in python从python中的类列表中随机选择x个项目
【发布时间】:2012-09-12 04:33:03
【问题描述】:

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

我创建了一个名为“列表”的类列表,其中包含 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

编辑 好的,这似乎有效。但是,它在 0x029990D0> 处返回此 ma​​in.Item 对象。我如何让它以上述格式返回?

【问题讨论】:

  • 不要在 python 中命名任何 list,因为这会影响内置类型。
  • 要从列表中选择 N 个随机元素,请使用 random.sample: docs.python.org/library/random.html

标签: python list class random jython


【解决方案1】:
i = 0
while i < randint(3, 20):
    # Display code here.
    i += 1

【讨论】:

  • randint 不是一个序列。 for i in randint(3, 20) 失败并返回 TypeError
  • 现在您将在每次循环时针对新的随机值测试i。一切都会好的,但你最好使用for i in xrange(randint(3, 20)):
【解决方案2】:

您可以使用random module 来选择一个介于 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)

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 你说“我希望它返回”到底是什么意思?
    猜你喜欢
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 2017-03-26
    • 2021-11-17
    • 1970-01-01
    • 2011-02-28
    • 2014-02-07
    • 2010-09-23
    相关资源
    最近更新 更多