sampling items from a nested list

Michael Spencer mahs at telcopartners.com
Wed Feb 16 20:15:42 EST 2005


Steven Bethard wrote:
> So, I have a list of lists, where the items in each sublist are of 
> basically the same form.  It looks something like:
> 
...
> 
> Can anyone see a simpler way of doing this?
> 
> Steve

You just make these up to keep us amused, don't you? ;-)

If you don't need to preserve the ordering, would the following work?:

  >>> data = [[('a', 0),
  ...          ('b', 1),
  ...          ('c', 2)],
  ...
  ...         [('d', 2),
  ...          ('e', 0)],
  ...
  ...         [('f', 0),
  ...          ('g', 2),
  ...          ('h', 1),
  ...          ('i', 0),
  ...          ('j', 0)]]
  ...
  >>> def resample2(data):
  ...     bag = {}
  ...     random.shuffle(data)
  ...     return [[(item, label)
  ...                 for item, label in group
  ...                     if bag.setdefault(label,[]).append(item)
  ...                         or len(bag[label]) < 3]
  ...                            for group in data if not random.shuffle(group)]
  ...
  >>> resample2(data)
[[('a', 0), ('c', 2), ('b', 1)], [('h', 1), ('g', 2), ('i', 0)], []]
  >>> resample2(data)
[[('h', 1), ('f', 0), ('j', 0), ('g', 2)], [('b', 1), ('c', 2)], []]
  >>> resample2(data)
[[('e', 0), ('d', 2)], [('i', 0), ('h', 1), ('g', 2)], [('b', 1)]]
  >>>

Michael




More information about the Python-list mailing list