本文整理汇总了Python中tabulate.tabulate函数的典型用法代码示例。如果您正苦于以下问题:Python tabulate函数的具体用法?Python tabulate怎么用?Python tabulate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tabulate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dumpProfile
def dumpProfile(self):
"""
Print region profiling information in a nice format.
"""
print "Profiling information for {}".format(type(self).__name__)
totalTime = 0.000001
for region in self.network.regions.values():
timer = region.computeTimer
totalTime += timer.getElapsed()
count = 1
profileInfo = []
for region in self.network.regions.values():
timer = region.computeTimer
count = max(timer.getStartCount(), count)
profileInfo.append([region.name,
timer.getStartCount(),
timer.getElapsed(),
100.0*timer.getElapsed()/totalTime,
timer.getElapsed()/max(timer.getStartCount(),1)])
profileInfo.append(["Total time", "", totalTime, "100.0", totalTime/count])
print tabulate(profileInfo, headers=["Region", "Count",
"Elapsed", "Pct of total", "Secs/iteration"],
tablefmt = "grid", floatfmt="6.3f")
if self.tmRegion is not None:
if self.tmRegion.getSpec().commands.contains("prettyPrintTraces"):
self.tmRegion.executeCommand(["prettyPrintTraces"])
示例2: printTableRowsAvg
def printTableRowsAvg(sumTuples, countTuples, columns):
rows = []
if len(sumTuples) == 1 and countTuples[0][0] == 0:
if len(columns) == 2:
rows.append(["NULL", "NULL"])
else:
rows.append(["NULL"])
print(tabulate(rows, headers = columns))
return
else:
if len(columns) == 2:
counts = dict(countTuples)
for row in sumTuples:
newRow = list(row)
encryptedSalaryHex = newRow[0]
encryptedSalary = newRow[0][:-1].decode('hex_codec')
encryptLength = len(encryptedSalary)
ffiUC_encryptedSalary = ffi.new("unsigned char[%i]" % encryptLength, encryptedSalary)
newRow[0] = float(int(cryptoLib.decrypt_num(cryptoLib.toData(ffiUC_encryptedSalary), keys.public, keys.private, encryptLength))) / counts[newRow[1]]
rows.append(newRow)
print(tabulate(rows, headers = columns))
return
else:
counts = countTuples[0][0]
for row in sumTuples:
newRow = list(row)
encryptedSalaryHex = newRow[0]
encryptedSalary = newRow[0][:-1].decode('hex_codec')
encryptLength = len(encryptedSalary)
ffiUC_encryptedSalary = ffi.new("unsigned char[%i]" % encryptLength, encryptedSalary)
newRow[0] = float(int(cryptoLib.decrypt_num(cryptoLib.toData(ffiUC_encryptedSalary), keys.public, keys.private, encryptLength))) / counts
rows.append(newRow)
print(tabulate(rows, headers = columns))
return
示例3: displayGraph
def displayGraph(ingredientMap):
# Display graph
# list of foods
foodNodes = ingredientMap.m.values()
# table for display
numNodeComb = 0
numNodeSep = 0
displayTable = [ [row,"nameFood",[]] for row in range(len(foodNodes)) ]
for eachFood in foodNodes:
displayTable[eachFood.getIndex()][1] = eachFood.getName()
for i,each in enumerate(ingredientMap.adjList):
stringChild = [str(eachChild) for eachChild in each ]
if (len(stringChild) > 1):
numNodeSep +=1
elif (len(stringChild) == 1):
numNodeComb += 1
stringChild = ",".join(stringChild)
displayTable[i][2] = stringChild
# global countComb, countSep
# countComb += numNodeComb
# countSep += numNodeSep
print tabulate(displayTable, headers=["node-id","node-form", "child-id"])
# originalTextsWithEdge = []
# for each in originalTexts:
# if each in dictTextEdge.keys():
# originalTextsWithEdge.append("\nEDGE:"+each +'\n'+ str(dictTextEdge[each])+"\n")
# else:
# originalTextsWithEdge.append(each)
示例4: load_lots_of_items
def load_lots_of_items():
char = poe_lib.Character()
js = open("items.json").read().strip().decode('ascii', 'ignore')
items = json.loads(js)
weapon_types = {}
words = {}
for _, item, _ in items:
if isinstance(item, dict):
typ = item['typeLine'].lower()
for word in typ.split(" "):
words.setdefault(word, 0)
words[word] += 1
checks = ['sword', 'mace', 'stave', 'flask', 'shield', 'greaves', 'boots']
for check in checks:
if check in typ:
weapon_types.setdefault(check, 0)
weapon_types[check] += 1
break
else:
weapon_types.setdefault("unk", 0)
weapon_types["unk"] += 1
pprint.pprint(sorted(words.items(), key=lambda a: a[1]))
pprint.pprint(sorted(weapon_types.items(), key=lambda a: a[1]))
data = [eff.tabulate() for eff in char.effects]
print tabulate.tabulate(data, headers=["Effect Magnitude", "Requirement to Effect", "Effects", "Source", "Original Text"])
示例5: highest_dividend
def highest_dividend():
nshares = defaultdict(lambda: 1)
for order in orders():
nshares[order[1]] = nshares[order[1]] + order[3]
sortsec = sorted(securities(), key=(lambda x: x[1] * x[2] / nshares[x[0]]), reverse=True)
table = map(lambda sec: [sec[0], sec[1] * sec[2] / nshares[sec[0]], sec[1] * sec[2], nshares[sec[0]]], sortsec)
print tabulate(table, headers=["Ticker", "Dividend per Share", "Total Dividend", "Shares being traded"])
示例6: show
def show(self, header=True):
print
if header: print self.table_header + ":"
print
table = copy.deepcopy(self.cell_values)
print tabulate.tabulate(table, headers=self.col_header, numalign="left", stralign="left")
print
示例7: bridgemem_details
def bridgemem_details(self):
"""
:return: list vlans or bridge names of various stp states MODIFY
"""
if not self.iface.is_bridgemem():
return None
# check if port is in STP
_str = ''
_stpstate = self.iface.stp.state
# get the list of states by grabbing all the keys
if self.iface.vlan_filtering:
_vlanlist = self.iface.vlan_list
_header = [_("all vlans on l2 port")]
_table = [[', '.join(linux_common.create_range('', _vlanlist))]]
_str += tabulate(_table, _header, numalign='left') + self.new_line()
_header = [_("untagged vlans")]
_table = [[', '.join(self.iface.native_vlan)]]
_str += tabulate(_table, _header, numalign='left') + self.new_line()
for _state, _bridgelist in _stpstate.items():
if _bridgelist:
_header = [_("vlans in %s state") %
(inflection.titleize(_state))]
# if vlan aware and bridgelist is not empty, then assume
# all vlans have that stp state
if self.iface.vlan_filtering:
_table = [[', '.join(linux_common.create_range(
'', _vlanlist))]]
else:
_table = [self._pretty_vlanlist(_bridgelist)]
_str += tabulate(_table, _header, numalign='left') + self.new_line()
return _str
示例8: main
def main():
parser = argparse.ArgumentParser(
description='Finds spare change using CSV exported from Mint!')
parser.add_argument('filename', type=str,
help='Filename to read for csv.')
parser.add_argument('-y', '--years', type=int, default=5,
help='The number of previous years (including current) to print.')
args = parser.parse_args()
# Ensure that the file exists that user provides.
if not os.path.isfile(args.filename):
print "ERROR: {0} does not exist! Please specify a valid file!".format(
args.filename)
sys.exit(1)
# Determine the start date for grabbing the values.
TODAY = datetime.datetime.now()
start_date = datetime.datetime(
TODAY.year - args.years + 1,
1,
1)
spare_change = collections.OrderedDict(
{"Month" : calendar.month_abbr[1:13] + ["Total"]})
# Open the CSV file and parse each row.
with open(args.filename, 'rb') as csvfile:
dictreader = csv.DictReader(csvfile)
for row in dictreader:
date = datetime.datetime.strptime(row['Date'], '%m/%d/%Y')
# If the date is greater than the start date, accumlate values.
if date > start_date:
# See if the year exist in the dictionary yet and create
# the list if not. We use None here instead of 0 so the table
# does not print values that are zero.
if date.year not in spare_change:
spare_change[date.year] = [None] * (MONTHS_IN_YEAR + 1)
# Calculate the change and then add the amount to the list
# in the dictionary. Index is the month offset by 1 since
# the list starts with 0.
dollars = float(row['Amount'])
change = dollars - math.floor(dollars)
if spare_change[date.year][date.month - 1] is None:
spare_change[date.year][date.month - 1] = change
else:
spare_change[date.year][date.month - 1] += change
if spare_change[date.year][12] is None:
spare_change[date.year][12] = change
else:
spare_change[date.year][12] += change
# Print the results.
print tabulate(spare_change, headers="keys", floatfmt=".2f")
示例9: head
def head(self, rows=10, cols=200, **kwargs):
"""
Analgous to R's `head` call on a data.frame. Display a digestible chunk of the H2OFrame starting from the beginning.
:param rows: Number of rows to display.
:param cols: Number of columns to display.
:param kwargs: Extra arguments passed from other methods.
:return: None
"""
if self._vecs is None or self._vecs == []:
raise ValueError("Frame Removed")
nrows = min(self.nrow(), rows)
ncols = min(self.ncol(), cols)
colnames = self.names()[0:ncols]
fr = H2OFrame.py_tmp_key()
cbind = "(= !" + fr + " (cbind %"
cbind += " %".join([vec._expr.eager() for vec in self]) + "))"
res = h2o.rapids(cbind)
h2o.remove(fr)
head_rows = [range(1, nrows + 1, 1)]
head_rows += [rows[0:nrows] for rows in res["head"][0:ncols]]
head = zip(*head_rows)
print "First", str(nrows), "rows and first", str(ncols), "columns: "
print tabulate.tabulate(head, headers=["Row ID"] + colnames)
print
示例10: processDatabase
def processDatabase(dbfile,free_params):
con = sqlite3.connect(dbfile)
cur = con.cursor()
cur.execute('SELECT ParamName,Value,GaussianPrior,Scale,Max,Min,Fixed from SystematicParams ORDER BY ParamName')
data = cur.fetchall()
try:
print tabulate(data,headers=["Name","Value","GaussianPrior","Scale","Max","Min","Fixed"],tablefmt="grid")
except:
print "PARAMETER TABLE: \n"
col_names = [col[0] for col in cur.description]
print " %s %s %s %s %s %s %s" % tuple(col_names)
for row in data: print " %s %s %s %s %s %s %s" % row
# Convert all row's angles from degrees to rad:
for irow,row in enumerate(data):
if 'theta' in row[0]:
row = list(row)
row[1] = np.deg2rad(row[1])
if row[2] is not None:
row[2] = np.deg2rad(row[2])
row[4] = np.deg2rad(row[4])
row[5] = np.deg2rad(row[5])
data[irow] = row
params = {}
for row in data:
prior_dict = {'kind': 'uniform'} if row[2] is None else {'fiducial': row[1],
'kind': 'gaussian',
'sigma': row[2]}
params[row[0]] = {'value': row[1], 'range': [row[5],row[4]],
'fixed': bool(row[6]),'scale': row[3],
'prior': prior_dict}
# now make fixed/free:
if free_params is not None:
# modify the free params to include the '_ih'/'_nh' tags:
mod_free_params = []
for p in free_params:
if ('theta23' in p) or ('deltam31' in p):
mod_free_params.append(p+'_ih')
mod_free_params.append(p+'_nh')
else:
mod_free_params.append(p)
print "\nmod free params: ",mod_free_params
#Loop over the free params and set to fixed/free
for key in params.keys():
if key in mod_free_params: params[key]['fixed'] = False
else: params[key]['fixed'] = True
if not params[key]['fixed']:
print " Leaving parameter free: ",key
print " ...all others fixed!"
return params
示例11: __mk_volume_table
def __mk_volume_table(table, ty, headers=(), **kwargs):
if ty == 'global':
return tabulate(table, headers=headers, tablefmt=global_tablefmt, **kwargs)
elif ty == 'byweek':
return tabulate(table, headers=headers, tablefmt=byweek_tablefmt, **kwargs)
elif ty == 'rank':
return tabulate(table, headers=headers, tablefmt=rank_tablefmt, **kwargs)
示例12: print_tabulate
def print_tabulate(res, noheader=False, short=False):
config = read_config()
c = conn(config)
tbl = []
for i in res:
if not i.__dict__.has_key('passwordenabled'):
i.__setattr__('passwordenabled', 0)
if not i.__dict__.has_key('created'):
i.__setattr__('created', '')
if i.passwordenabled == 1:
passw = "Yes"
else:
passw = "No"
if short:
tbl.append(["%s/%s" % (i.account, i.name)])
else:
tbl.append([
"%s/%s" % (i.account, i.name),
i.zonename,
i.ostypename,
i.created,
passw,
])
tbl = sorted(tbl, key=operator.itemgetter(0))
if (noheader or short):
print tabulate(tbl, tablefmt="plain")
else:
tbl.insert(0, ['name', 'zone', 'ostype', 'created', 'passwordenabled'])
print tabulate(tbl, headers="firstrow")
示例13: pprint
def pprint(cls, struct, data=None, format='pprint'):
# TODO: maybe refactor to struct._pprint_
name = struct._name_()
payload = struct._dump_()
payload_hex = hexlify(payload)
if data:
payload_data = list(data.items())
else:
payload_data = list(cls.to_dict(struct).items())
if format == 'pprint':
print 'name:', name
print 'hex: ', payload_hex
pprint(payload_data, indent=4, width=42)
elif format == 'tabulate-plain':
separator = ('----', '')
output = [
separator,
('name', name),
separator,
]
output += StructAdapter.binary_reprs(payload)
output += [separator]
output += payload_data
print tabulate(output, tablefmt='plain')
#print tabulate(list(meta.items()), tablefmt='plain')
#print tabulate(payload_data, missingval='n/a', tablefmt='simple')
else:
raise ValueError('Unknown format "{}" for pretty printer'.format(format))
示例14: showPfcAsym
def showPfcAsym(interface):
"""
PFC handler to display asymmetric PFC information.
"""
i = {}
table = []
key = []
header = ('Interface', 'Asymmetric')
configdb = swsssdk.ConfigDBConnector()
configdb.connect()
if interface:
db_keys = configdb.keys(configdb.CONFIG_DB, 'PORT|{0}'.format(interface))
else:
db_keys = configdb.keys(configdb.CONFIG_DB, 'PORT|*')
for i in db_keys or [None]:
if i:
key = i.split('|')[-1]
if key and key.startswith('Ethernet'):
entry = configdb.get_entry('PORT', key)
table.append([key, entry.get('pfc_asym', 'N/A')])
sorted_table = natsorted(table)
print '\n'
print tabulate(sorted_table, headers=header, tablefmt="simple", missingval="")
print '\n'
示例15: show_summary_all
def show_summary_all(db_server, db_port, db_name, db_collection):
pattern = {}
print "-" * 60
print "Summary Data: "
print "-" * 60
data = pns_mongo.pns_search_results_from_mongod(db_server,
db_port,
db_name,
db_collection,
pattern)
for record in data:
print_record_header(record)
for flow in record['flows']:
print_flow_header(flow)
# Display the results for each flow.
cols = ['throughput_kbps', 'protocol', 'tool',
'rtt_ms', 'loss_rate', 'pkt_size',
'rtt_avg_ms']
result_list = get_results_info(flow['results'], cols)
print tabulate.tabulate(result_list,
headers="keys", tablefmt="grid")
print "\n"