Randomly select x number of elements from class list in python

In jython, I have an object class defined as follows:

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 created a list of classes called a β€œlist” of elements in a class with 4000 lines that look like this:

 'PO78141', 13, ' B ', 40 

I am trying to randomly select a number in the range of 3 to 20, called x. Then the code will select x the 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 Well, this works. However, it returns this < main .Item object in 0x029990D0>. How can I return it in the format above?

+6
source share
3 answers

You can use the random module to select a number from 3 to 20, and take a sample of the 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) 
+12
source

Note. I renamed the list to lst . Assuming 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) 
0
source
 i = 0 while i < randint(3, 20): # Display code here. i += 1 
-1
source

Source: https://habr.com/ru/post/925795/


All Articles