8 examples of 'how to make a table in python' in Python

Every line of 'how to make a table in python' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
15def makeTable(table,name,keyLookup):
16
17 print "[HIDE="+name+"][CODE]"
18 print "Combined usage for "+name
19 print " + ---- + ------------------ + ------- + "
20 print " | Rank | Pokemon | Percent | "
21 print " + ---- + ------------------ + ------- + "
22 print ' | %-4d | %-18s | %6.3f%% |' % (1,keyLookup[table[0][0]],table[0][1]*100)
23 for i in range(1,len(table)):
24 if table[i][1] < 0.001:
25 break
26 print ' | %-4d | %-18s | %6.3f%% |' % (i+1,keyLookup[table[i][0]],100.0*table[i][1])
27 print " + ---- + ------------------ + ------- + "
28 print "[/CODE][/HIDE]"
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

131def make_table(contents, headers=None):
132 """Given a numpy ndarray of strings, concatenate them into a html table.
133
134 Args:
135 contents: A np.ndarray of strings. May be 1d or 2d. In the 1d case, the
136 table is laid out vertically (i.e. row-major).
137 headers: A np.ndarray or list of string header names for the table.
138
139 Returns:
140 A string containing all of the content strings, organized into a table.
141
142 Raises:
143 ValueError: If contents is not a np.ndarray.
144 ValueError: If contents is not 1d or 2d.
145 ValueError: If contents is empty.
146 ValueError: If headers is present and not a list, tuple, or ndarray.
147 ValueError: If headers is not 1d.
148 ValueError: If number of elements in headers does not correspond to number
149 of columns in contents.
150 """
151 if not isinstance(contents, np.ndarray):
152 raise ValueError('make_table contents must be a numpy ndarray')
153
154 if contents.ndim not in [1, 2]:
155 raise ValueError('make_table requires a 1d or 2d numpy array, was %dd' %
156 contents.ndim)
157
158 if headers:
159 if isinstance(headers, list) or isinstance(headers, tuple):
160 headers = np.array(headers)
161 if not isinstance(headers, np.ndarray):
162 raise ValueError('Could not convert headers %s into np.ndarray' % headers)
163 if headers.ndim != 1:
164 raise ValueError('Headers must be 1d, is %dd' % headers.ndim)
165 expected_n_columns = contents.shape[1] if contents.ndim == 2 else 1
166 if headers.shape[0] != expected_n_columns:
167 raise ValueError('Number of headers %d must match number of columns %d' %
168 (headers.shape[0], expected_n_columns))
169 header = '<thead>\n%s</thead>\n' % make_table_row(headers, tag='th')
170 else:
171 header = ''
172
173 n_rows = contents.shape[0]
174 if contents.ndim == 1:
175 # If it's a vector, we need to wrap each element in a new list, otherwise
176 # we would turn the string itself into a row (see test code)
177 rows = (make_table_row([contents[i]]) for i in range(n_rows))
178 else:
179 rows = (make_table_row(contents[i, :]) for i in range(n_rows))
180
181 return '<table>\n%s<tbody>\n%s</tbody>\n</table>' % (header, ''.join(rows))
49def makeTable(values, height, width):
50 lines = [[] for i in range(height + 1)]
51 firstRowString = "|{}" + "+{}" * (len(values) - 1) + '|'
52 rowString = "|{}" * len(values) + '|'
53 cWidth = (width // len(values)) - 1
54 cRemainder = width % len(values) - 1
55 for title, rows in values.items():
56 if cRemainder > 0:
57 heading = "{1:-^{0}}".format(cWidth + 1, title)
58 cRemainder -= 1
59 elif cRemainder < 0:
60 heading = "{1:-^{0}}".format(cWidth - 1, title)
61 cRemainder += 1
62 else:
63 heading = "{1:-^{0}}".format(cWidth, title)
64 hWidth = len(heading)
65 lines[0].append(heading)
66 if len(rows) < height:
67 for i in range(height - len(rows)):
68 rows.append(('NA', -1))
69 for index, entry in enumerate((prepEntry(hWidth, *s) for s in rows[:height]), start = 1):
70 lines[index].append(entry)
71 retLines = []
72 retLines.append(firstRowString.format(*tuple(lines[0])))
73 for line in lines[1:]:
74 retLines.append(rowString.format(*tuple(line)))
75 return '\n'.join(retLines)
4def as_table(dicts: List[Dict[str, Any]], keys: List[str] = None) -> List[List[str]]:
5 """
6 Converts a list of dictionaries to a nested list, ordered by specified keys.
7
8 :param keys: ordered list of keys to include in each row, or None to use the keys for the first dict
9 :param dicts: list of dictionaries
10 :return:
11 """
12 if not dicts:
13 return []
14
15 if keys is None:
16 keys = list(dicts[0].keys())
17 return [keys] + [[str(d.get(f, "")) if d.get(f, "") is not None else None for f in keys] for d in dicts]
379def get_table(table):
380 col_width = [max(len(x) for x in col) for col in zip(*table)]
381 table_string = []
382 for line in table:
383 table_string.append('| %s | %s | %s |' % (line[0].rjust(col_width[0]), line[1].rjust(col_width[1]), line[2].rjust(col_width[2])))
384 return "\n".join(table_string) + "\n"
33def _Table(*args, **kwargs):
34 """
35 if passing (name, column, ..), existing metadata will be added to args,
36 return Table(name, metadata, column, ..)
37 """
38 if len(args) > 1 and isinstance(args[1], db.Column):
39 args = (args[0], db.metadata) + args[1:]
40 return sqlalchemy.Table(*args, **kwargs)
33def _list_table(headers, data, title='', columns=None):
34 """Build a list-table directive.
35
36 :param add: Function to add one row to output.
37 :param headers: List of header values.
38 :param data: Iterable of row data, yielding lists or tuples with rows.
39 """
40 yield '.. list-table:: %s' % title
41 yield ' :header-rows: 1'
42 if columns:
43 yield ' :widths: %s' % (','.join(str(c) for c in columns))
44 yield ''
45 yield ' - * %s' % headers[0]
46 for h in headers[1:]:
47 yield ' * %s' % h
48 for row in data:
49 yield ' - * %s' % row[0]
50 for r in row[1:]:
51 yield ' * %s' % r
7def make_pythons():
8 t = wt.Table("pythons.wt")
9 t.add_id_column(1)
10 t.add_char_column("name")
11 t.add_uint_column("born")
12 t.add_uint_column("writer")
13 t.add_uint_column("actor")
14 t.add_uint_column("director")
15 t.add_uint_column("producer")
16 t.open("w")
17 rows = [
18 [b"John Cleese", 1939, 60, 127, 0, 43],
19 [b"Terry Gilliam", 1940, 25, 24, 18, 8],
20 [b"Eric Idle", 1943, 38, 74, 7, 5],
21 [b"Terry Jones", 1942, 50, 49, 16, 1],
22 [b"Michael Palin", 1943, 58, 56, 0, 1],
23 [b"Graham Chapman", 1941, 46, 24, 0, 2]
24 ]
25 for r in rows:
26 t.append([None] + r)
27 t.close()

Related snippets