Display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough).
(self, list, displaywidth=80)
| 357 | self.stdout.write("\n") |
| 358 | |
| 359 | def columnize(self, list, displaywidth=80): |
| 360 | """Display a list of strings as a compact set of columns. |
| 361 | |
| 362 | Each column is only as wide as necessary. |
| 363 | Columns are separated by two spaces (one was not legible enough). |
| 364 | """ |
| 365 | if not list: |
| 366 | self.stdout.write("<empty>\n") |
| 367 | return |
| 368 | |
| 369 | nonstrings = [i for i in range(len(list)) |
| 370 | if not isinstance(list[i], str)] |
| 371 | if nonstrings: |
| 372 | raise TypeError("list[i] not a string for i in %s" |
| 373 | % ", ".join(map(str, nonstrings))) |
| 374 | size = len(list) |
| 375 | if size == 1: |
| 376 | self.stdout.write('%s\n'%str(list[0])) |
| 377 | return |
| 378 | # Try every row count from 1 upwards |
| 379 | for nrows in range(1, len(list)): |
| 380 | ncols = (size+nrows-1) // nrows |
| 381 | colwidths = [] |
| 382 | totwidth = -2 |
| 383 | for col in range(ncols): |
| 384 | colwidth = 0 |
| 385 | for row in range(nrows): |
| 386 | i = row + nrows*col |
| 387 | if i >= size: |
| 388 | break |
| 389 | x = list[i] |
| 390 | colwidth = max(colwidth, len(x)) |
| 391 | colwidths.append(colwidth) |
| 392 | totwidth += colwidth + 2 |
| 393 | if totwidth > displaywidth: |
| 394 | break |
| 395 | if totwidth <= displaywidth: |
| 396 | break |
| 397 | else: |
| 398 | nrows = len(list) |
| 399 | ncols = 1 |
| 400 | colwidths = [0] |
| 401 | for row in range(nrows): |
| 402 | texts = [] |
| 403 | for col in range(ncols): |
| 404 | i = row + nrows*col |
| 405 | if i >= size: |
| 406 | x = "" |
| 407 | else: |
| 408 | x = list[i] |
| 409 | texts.append(x) |
| 410 | while texts and not texts[-1]: |
| 411 | del texts[-1] |
| 412 | for col in range(len(texts)): |
| 413 | texts[col] = texts[col].ljust(colwidths[col]) |
| 414 | self.stdout.write("%s\n"%str(" ".join(texts))) |