Advertisement
Guest User

Untitled

a guest
Dec 15th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. # ----------------------------------------------------------------------------
  2. # Split a list into a number of sublists, e.g. sublist([1,2,3,4,5,6,7],3) ->
  3. # [[1,2,3],[4,5,6],[7]]. This probably doesn't need to be a method at all
  4. # since it's basically just a simple list comprehension but I can remember it
  5. # easier this way.
  6. # ----------------------------------------------------------------------------
  7. def sublist(arg, size):
  8. i = 0
  9.  
  10. # List comprehensions ftw!
  11. return [arg[i:i+size] for i in range(0, len(arg), size)]
  12.  
  13.  
  14. # ----------------------------------------------------------------------------
  15. # Columnize a list of strings using evtable. Handles unicode and markup,
  16. # including ANSI.
  17. # ----------------------------------------------------------------------------
  18. def columnize(items, width=80, cols=3):
  19.  
  20. # Initialize a new table. No fancy border or headers, we just want a grid
  21. # of plain text (with any markup intact, of course).
  22. table = evtable.EvTable(border='none', width=width)
  23.  
  24. # Split our list into a number of sublists. The length of each sublist
  25. # will be equal to the number of desired columns. This allows us to add
  26. # an entire row at once without needing a second loop to add the columns
  27. # for each row.
  28. out = sublist(items, cols)
  29.  
  30. # Make sure that we were given enough data to fill at least one row
  31. # with the desired number of columns. Without this check, the calls to
  32. # reformat_column may fail if you try to format more columns than you
  33. # passed data to fill.
  34. actual_len = len(out[0])
  35.  
  36. # Add each row.
  37. for x in out:
  38. table.add_row(*x)
  39.  
  40. # Calculate the width of each column.
  41. col_width = width / cols
  42.  
  43. # Configure the columns to the desired width.
  44. for x in range(0, actual_len-1):
  45. table.reformat_column(x, width=col_width)
  46.  
  47. # Return the table.
  48. return unicode(table)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement