本文整理匯總了Python中operator.itemgetter方法的典型用法代碼示例。如果您正苦於以下問題:Python operator.itemgetter方法的具體用法?Python operator.itemgetter怎麽用?Python operator.itemgetter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類operator
的用法示例。
在下文中一共展示了operator.itemgetter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_by_calendar
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def get_by_calendar(self, calendar_id, offset=0, limit=500):
"""
獲取日曆下的日程列表
https://work.weixin.qq.com/api/doc/90000/90135/92626
(注意,被取消的日程也可以拉取詳情,調用者需要檢查status)
:param calendar_id: 日曆ID
:param offset: 分頁,偏移量, 默認為0
:param limit: 分頁,預期請求的數據量,默認為500,取值範圍 1 ~ 1000
:return: 日程列表
:rtype: list[dict]
"""
return self._post(
"oa/schedule/get_by_calendar",
data={"cal_id": calendar_id, "offset": offset, "limit": limit},
result_processor=op.itemgetter("schedule_list"),
)
示例2: add
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def add(self, organizer, summary, color, description="", shares=()):
"""
創建日曆
https://work.weixin.qq.com/api/doc/90000/90135/92618
:param organizer: 指定的組織者userid。注意該字段指定後不可更新
:param summary: 日曆標題。1 ~ 128 字符
:param color: 日曆在終端上顯示的顏色,RGB顏色編碼16進製表示,例如:”#0000FF” 表示純藍色
:param description: 日曆描述。0 ~ 512 字符
:param shares: 日曆共享成員列表。最多2000人
:type shares: list[str]
:return: 日曆ID
:rtype: str
"""
data = {
"calendar": {
"organizer": organizer,
"summary": summary,
"color": color,
"description": description,
"shares": [{"userid": userid} for userid in shares],
}
}
return self._post("oa/calendar/add", data=data, result_processor=op.itemgetter("cal_id"))
示例3: address_count
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def address_count(trace):
"""
Count the diffetent occurences of the addresses in the trace and return a sorted(highest->lowest) occurence list
:param trace: execution trace of the binary
:return: sorted list starting with the highest address count and ending with the lowest
"""
trace = [line.addr for line in trace]
analysis_result = {}
for addr in trace:
# for heuristic analysis the count of address
count = trace.count(addr)
if addr not in analysis_result.keys():
analysis_result[addr] = count
# sort the analysis result by most common addresses
sorted_result = sorted(analysis_result.items(), key=operator.itemgetter(1))
sorted_result.reverse()
return sorted_result
示例4: score_function_all_class
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def score_function_all_class(self, x, W):
score_list = {}
ovo_vote = []
for class_item in self.class_list:
score = self.score_function(x, W[class_item])
if self.decomposition == 'ovo':
if score >= 0.5:
score_list[class_item] = class_item[0]
else:
score_list[class_item] = class_item[1]
ovo_vote.append(score_list[class_item])
elif self.decomposition == 'ova':
score_list[class_item] = score
if self.decomposition == 'ovo':
return max(set(ovo_vote), key=ovo_vote.count)
elif self.decomposition == 'ova':
return max(score_list.items(), key=operator.itemgetter(1))[0]
示例5: update
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def update(self, labels, preds):
label_weight = labels[1].asnumpy()
preds = preds[0].asnumpy()
tmp = []
for i in range(preds.shape[0]):
for j in range(preds.shape[1]):
tmp.append((label_weight[i][j], preds[i][j]))
tmp = sorted(tmp, key=itemgetter(1), reverse=True)
m = 0.0
n = 0.0
z = 0.0
k = 0
for a, _ in tmp:
if a > 0.5:
m += 1.0
z += len(tmp) - k
else:
n += 1.0
k += 1
z -= m * (m + 1.0) / 2.0
z /= m
z /= n
self.sum_metric += z
self.num_inst += 1
示例6: list_chutes
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def list_chutes(ctx):
"""
List chutes in the store that you own or have access to.
"""
client = ControllerClient()
result = client.list_chutes()
if len(result) > 0:
click.echo("Name Ver Description")
for chute in sorted(result, key=operator.itemgetter('name')):
# Show the summary if available. This is intended to be
# a shorter description than the description field.
summary = chute.get('summary', None)
if summary is None:
summary = chute.get('description', '')
click.echo("{:32s} {:3d} {}".format(chute['name'],
chute['current_version'], summary))
return result
示例7: list_versions
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def list_versions(ctx, name):
"""
List versions of a chute in the store.
NAME must be the name of a chute in the store.
"""
client = ControllerClient()
result = client.list_versions(name)
if len(result) > 0:
click.echo("Version GitCheckout")
for version in sorted(result, key=operator.itemgetter('version')):
try:
code = version['config']['download']['checkout']
except:
code = "N/A"
click.echo("{:7s} {}".format(str(version['version']), code))
return result
示例8: sort_by_column
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def sort_by_column(self, csv_cont, col, reverse=False):
"""
Sorts CSV contents by column name (if col argument is type <str>)
or column index (if col argument is type <int>).
"""
header = csv_cont[0]
body = csv_cont[1:]
if isinstance(col, str):
col_index = header.index(col)
else:
col_index = col
body = sorted(body,
key=operator.itemgetter(col_index),
reverse=reverse)
body.insert(0, header)
return body
示例9: build_index
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def build_index():
repo_directory = get_config()['repo_directory']
index_path = path.join(repo_directory, 'pages', 'index.json')
page_path = path.join(repo_directory, 'pages')
tree_generator = os.walk(page_path)
folders = next(tree_generator)[1]
commands, new_index = {}, {}
for folder in folders:
pages = next(tree_generator)[2]
for page in pages:
command_name = path.splitext(page)[0]
if command_name not in commands:
commands[command_name] = {'name': command_name,
'platform': [folder]}
else:
commands[command_name]['platform'].append(folder)
command_list = [item[1] for item in
sorted(commands.items(), key=itemgetter(0))]
new_index['commands'] = command_list
with open(index_path, mode='w') as f:
json.dump(new_index, f)
示例10: _spanning_iterator
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def _spanning_iterator(self):
''' implements basic spanning on the python side operating on Rows '''
# TODO implement in Java and support not only Rows
columns = set(str(c) for c in self.columns)
def spanning_iterator(partition):
def key_by(columns):
for row in partition:
k = Row(**{c: row.__getattr__(c) for c in columns})
for c in columns:
del row[c]
yield (k, row)
for g, l in groupby(key_by(columns), itemgetter(0)):
yield g, list(_[1] for _ in l)
return spanning_iterator
示例11: run
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def run(self):
try:
words = self.model.CORPORA[self.name]()
from operator import itemgetter
text = [w for w in words if len(w) > 2]
fd = FreqDist(tuple(text[i:i+2]) for i in range(len(text)-1))
vocab = FreqDist(text)
scored = [((w1,w2), fd[(w1,w2)] ** 3 / float(vocab[w1] * vocab[w2])) for w1, w2 in fd]
scored.sort(key=itemgetter(1), reverse=True)
self.model.collocations = list(map(itemgetter(0), scored))
self.model.queue.put(CORPUS_LOADED_EVENT)
except Exception as e:
print(e)
self.model.queue.put(ERROR_LOADING_CORPUS_EVENT)
#def collocations():
# colloc_strings = [w1 + ' ' + w2 for w1, w2 in self._collocations[:num]]
示例12: hypernym_distances
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def hypernym_distances(self, distance=0, simulate_root=False):
"""
Get the path(s) from this synset to the root, counting the distance
of each node from the initial node on the way. A set of
(synset, distance) tuples is returned.
:type distance: int
:param distance: the distance (number of edges) from this hypernym to
the original hypernym ``Synset`` on which this method was called.
:return: A set of ``(Synset, int)`` tuples where each ``Synset`` is
a hypernym of the first ``Synset``.
"""
distances = set([(self, distance)])
for hypernym in self._hypernyms() + self._instance_hypernyms():
distances |= hypernym.hypernym_distances(distance+1, simulate_root=False)
if simulate_root:
fake_synset = Synset(None)
fake_synset._name = '*ROOT*'
fake_synset_distance = max(distances, key=itemgetter(1))[1]
distances.add((fake_synset, fake_synset_distance+1))
return distances
示例13: get__repr__
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def get__repr__(self, params):
"""
Converts the object to a nicely printable string.
"""
def format_params(params):
if atLeastPython3:
items = params.items()
else:
items = list(params.items())
for k, v in sorted(items, key=itemgetter(0), reverse=True):
isText = isinstance(v, (str, unicode))
if isText and not atLeastPython3:
v = v.encode('utf-8')
yield '{k}="{v}"'.format(k=k, v=v) if isText else '{k}={v}'.format(k=k, v=v)
return '{class_name}({params})'.format(
class_name=self.__class__.__name__,
params=", ".join(list(format_params(params)))
)
示例14: rank
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def rank(self, x, threshold=None):
"""Returns ordered list with all labels ordered according to prob(x)
(e.g., [[3 1 2], [2 1 3], ...]).
The optional threshold parameter is used to exclude labels having equal
or less probability. E.g. threshold=0 excludes all labels with zero
probability.
"""
all_ranking = []
prob = self.prob(x)
for p in prob:
if threshold is None:
ranking = p.items()
else:
ranking = ((k, v) for k, v in p.items() if v > threshold)
result = [k for k, v in
sorted(ranking, key=operator.itemgetter(1), reverse=True)]
all_ranking.append(result)
return all_ranking
示例15: next_partition_candidate
# 需要導入模塊: import operator [as 別名]
# 或者: from operator import itemgetter [as 別名]
def next_partition_candidate(self, partitions, column_number, table,
num_new_partitions, maxdiff_map):
global_maxdiff = max(sorted(maxdiff_map.keys()))
partition, cid = maxdiff_map[global_maxdiff][0]
vals = partition.col_value_list[cid]
counter = collections.Counter(vals)
first_key = True
prev_key = None
diff = []
for key in sorted(counter.keys()):
if first_key:
first_key = False
prev_key = key
else:
spread = key - prev_key
diff.append((prev_key, (spread * counter[prev_key])))
prev_key = key
diff.append((prev_key, (0 * counter[prev_key])))
partition_boundaries = sorted(
list(
tp[0]
for tp in sorted(diff, key=operator.itemgetter(
1), reverse=True)[:min(num_new_partitions - 1, len(diff))]))
return (partitions.index(partition), cid, partition_boundaries,
global_maxdiff)