Sometimes, it is desirable to split a large python iterable into smaller iterables. I have developed a small module for Stockr which can be used to help with this common task.
Supported iterable types:
- Lists
- Most Basic Generators
- Dictionaries
- Django QuerySets
Module: List-Splitter
Usage:
import list_splitter inp_dict = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6 } inp_list = [ 1, 2, 3, 4, 5, 6 ] """ Prints: [ {'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6} ] """ print(list(list_splitter.n_chunks(inp_dict, 2))) """ Prints: [ [1, 2, 3], [4, 5, 6] ] """ print(list(list_splitter.n_chunks(inp_list, 2))) """ Prints: [ {'a': 1, 'c': 3}, {'b': 2, 'e': 5}, {'d': 4, 'f': 6} ] """ print(list(list_splitter.chunks_of_n(inp_dict, 2))) """ Prints: [ [1, 2], [3, 4], [5, 6] ] """ print(list(list_splitter.chunks_of_n(inp_list, 2))) """ Prints: [ [{'a': 1}, {'c': 3}], [{'b': 2}, {'e': 5}], [{'d': 4}, {'f': 6}] ] """ print(list(list_splitter.chunks_matrix(inp_dict, 1, 2))) """ Prints: [ [[1], [2]], [[3], [4]], [[5], [6]] ] """ print(list(list_splitter.chunks_matrix(inp_list, 1, 2))) """ Prints: [ [{'a': 1, 'c': 3}], [{'b': 2, 'e': 5}], [{'d': 4, 'f': 6}] ] """ print(list(list_splitter.chunks_matrix(inp_dict, 2, 1))) """ Prints: [ [[1, 2]], [[3, 4]], [[5, 6]] ] """ print(list(list_splitter.chunks_matrix(inp_list, 2, 1)))
3 comments:
I have tryed to use your function and I got the error
type: zip() argument after * must be a sequence, not dictionary-itemiterator
The error is produced in line
if isinstance(r, dict)
r was s dictionary and the result of the boolean expresion was True.
What´s wrong with it?
Best regards
José Luis Casado
I have tryed to use your function and I got the error
type: zip() argument after * must be a sequence, not dictionary-itemiterator
The error is produced in line
if isinstance(r, dict)
r was s dictionary and the result of the boolean expresion was True.
What´s wrong with it?
Best regards
José Luis Casado
José:
Thanks for pointing this out. I have now fixed the issue. The code for this is now on the Github page which is linked to from the post. I have also updated usage instructions.
Post a Comment