本文整理汇总了Python中tabulate.tabulate函数的典型用法代码示例。如果您正苦于以下问题:Python tabulate函数的具体用法?Python tabulate怎么用?Python tabulate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tabulate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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"])
开发者ID:Starcounter-Jack,项目名称:nupic.research,代码行数:29,代码来源:classify_network_api.py
示例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
开发者ID:maxstr,项目名称:cs174a_finalProject,代码行数:34,代码来源:dbClient.py
示例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)
开发者ID:MickJermsurawong,项目名称:buildSIMMR,代码行数:30,代码来源:getLabel.py
示例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"])
开发者ID:icook,项目名称:poe_lib,代码行数:28,代码来源:messy.py
示例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"])
开发者ID:ManasGeorge,项目名称:CodeB,代码行数:7,代码来源:clientpy2.py
示例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
开发者ID:StephaneFeniar,项目名称:h2o-dev,代码行数:7,代码来源:two_dim_table.py
示例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
开发者ID:benthomasson,项目名称:netshow-cumulus-lib,代码行数:33,代码来源:print_iface.py
示例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")
开发者ID:jmoles,项目名称:spare-change,代码行数:60,代码来源:spare_change.py
示例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
开发者ID:venkatesh12341234,项目名称:h2o-dev,代码行数:26,代码来源:frame.py
示例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
开发者ID:sonia3994,项目名称:pisa,代码行数:60,代码来源:generate_settings.py
示例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)
开发者ID:calixteman,项目名称:clouseau,代码行数:7,代码来源:statusflags.py
示例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")
开发者ID:cldmnky,项目名称:rbc-tools,代码行数:30,代码来源:template.py
示例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))
开发者ID:hiveeyes,项目名称:kotori,代码行数:32,代码来源:c.py
示例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'
开发者ID:Azure,项目名称:sonic-utilities,代码行数:32,代码来源:main.py
示例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"
开发者ID:mikeynap,项目名称:vmtp,代码行数:26,代码来源:pnsdb_summary.py
示例16: tail
def tail(self, rows=10, cols=200, **kwargs):
"""
Analgous to R's `tail` call on a data.frame. Display a digestible chunk of the H2OFrame starting from the end.
: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]
exprs = [self[c][(self.nrow()-nrows):(self.nrow())] for c in range(ncols)]
print "Last", str(nrows), "rows and first", str(ncols), "columns: "
if nrows != 1:
fr = H2OFrame.py_tmp_key()
cbind = "(= !" + fr + " (cbind %"
cbind += " %".join([expr.eager() for expr in exprs]) + "))"
res = h2o.rapids(cbind)
h2o.remove(fr)
tail_rows = [range(self.nrow()-nrows+1, self.nrow() + 1, 1)]
tail_rows += [rows[0:nrows] for rows in res["head"][0:ncols]]
tail = zip(*tail_rows)
print tabulate.tabulate(tail, headers=["Row ID"] + colnames)
else:
print tabulate.tabulate([[self.nrow()] + [expr.eager() for expr in exprs]], headers=["Row ID"] + colnames)
print
开发者ID:venkatesh12341234,项目名称:h2o-dev,代码行数:30,代码来源:frame.py
示例17: print_events
def print_events(conn, stack_name, follow, lines=100, from_dt=datetime.fromtimestamp(0, tz=pytz.UTC)):
"""Prints tabulated list of events"""
events_display = []
seen_ids = set()
next_token = None
while True:
events, next_token = get_events(conn, stack_name, next_token)
status = get_stack_status(conn, stack_name)
normalize_events_timestamps(events)
if follow:
events_display = [(ev.timestamp.astimezone(tzlocal.get_localzone()), ev.resource_status, ev.resource_type,
ev.logical_resource_id, ev.resource_status_reason) for ev in events
if ev.event_id not in seen_ids and ev.timestamp >= from_dt]
if len(events_display) > 0:
print(tabulate(events_display, tablefmt='plain'), flush=True)
seen_ids |= set([event.event_id for event in events])
if status not in IN_PROGRESS_STACK_STATES and next_token is None:
break
if next_token is None:
time.sleep(5)
else:
events_display.extend([(event.timestamp.astimezone(tzlocal.get_localzone()), event.resource_status,
event.resource_type, event.logical_resource_id, event.resource_status_reason)
for event in events])
if len(events_display) >= lines or next_token is None:
break
if not follow:
print(tabulate(events_display[:lines], tablefmt='plain'), flush=True)
return status
开发者ID:cfstacks,项目名称:stacks,代码行数:32,代码来源:cf.py
示例18: describe
def describe(self):
"""
Generate an in-depth description of this H2OFrame.
The description is a tabular print of the type, min, max, sigma, number of zeros,
and number of missing elements for each H2OVec in this H2OFrame.
:return: None (print to stdout)
"""
if self._vecs is None or self._vecs == []:
raise ValueError("Frame Removed")
print "Rows:", len(self._vecs[0]), "Cols:", len(self)
headers = [vec._name for vec in self._vecs]
table = [
self._row('type', None),
self._row('mins', 0),
self._row('mean', None),
self._row('maxs', 0),
self._row('sigma', None),
self._row('zero_count', None),
self._row('missing_count', None)
]
chunk_summary_tmp_key = H2OFrame.send_frame(self)
chunk_summary = h2o.frame(chunk_summary_tmp_key)["frames"][0]["chunk_summary"]
h2o.remove(chunk_summary_tmp_key)
print tabulate.tabulate(table, headers)
print
print chunk_summary
print
开发者ID:venkatesh12341234,项目名称:h2o-dev,代码行数:33,代码来源:frame.py
示例19: sensorInfos
def sensorInfos(args):
requireSensorID(args)
params = extractParams(args)
if 'tail' not in params:
params['tail'] = 1
obj = lib.Sensor(args.directory, args.sensorid, args.type)
infos = obj.SensorInfos(**params)
if not infos:
print "Not enought datas for %s" % args.sensorid
sys.exit(1)
showresult = [
['Sensorid', args.sensorid],
#['Sensor Type', obj.configs['type']],
['NB lines', str(infos['nblines'])],
['Min date', format_datetime(infos['mindate'])],
['Max date', format_datetime(infos['maxdate'])],
['Min value', '%s (%s)' % (str(infos['minvalue']), format_datetime(infos['minvaluedate']))],
['Max value', '%s (%s)' % (str(infos['maxvalue']), format_datetime(infos['maxvaluedate']))],
# ['Avg size', str(infos['avgsize'])],
['Avg value', str(infos['avgvalue'])],
['Avg delta (round ratio)', str(infos['avgdelta'])],
# ['Total size', '%s Mo' % str(infos['avgsize'] * infos['nblines'] / 1024 / 1024.0)],
]
header = ['Title', 'Value']
print tabulate(showresult, headers=header)
开发者ID:badele,项目名称:serialkiller,代码行数:30,代码来源:sk_command.py
示例20: after
def after(self):
def fmt_date(dt):
if not dt:
return ''
return dt.strftime('%Y-%m-%d %H:%M')
def fmt_dur(d):
if not d:
return ''
return '%0.1f' % (d / 60.0)
s=Storage(self.config['storage_root'])
stats=s.get_status()
tab=[]
for vm in self.result:
stat=stats.get(vm)
row=self.result[vm]
if stat:
row.append(fmt_date(stat['last_backup']))
row.append(fmt_dur(stat['duration']))
else:
row.extend(['', ''])
tab.append(row)
for vm in stats:
if not self.result.has_key(vm):
tab.append(['', vm, '', '', '', fmt_date(stats[vm]['last_backup']), fmt_dur(stats[vm]['duration'])])
print tabulate(tab, ['Host', 'VM', 'State', 'AutoBck', 'AutoBck Batch', 'Last Backup', 'Dur. (m)'])
开发者ID:terbolous,项目名称:xapi-back,代码行数:25,代码来源:list.py
注:本文中的tabulate.tabulate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论