猿问

使用 Python 使用 elasticsearch json 对象的元素、合同桥分数进行计算

作为我的中间尝试,没有尝试遍历不同的电路板。此数据仅由搜索所有查询生成。


@application.route('/', methods=['GET', 'POST'])

def index():

    search = {"query": {"match_all": {}}}

    resp = es.search(index="matchpoints", doc_type="score", body = search)

    rows = extract_rows(resp)

    for board in rows:

        scores = score_board(board)

        report(scores)

        print(report(scores))

    return 'ok'


def extract_rows(resp):                                                                                                          

    """Extract the rows for the board from the query response."""                                                                

    # Based on the data structure provided by the OP.                                                          

    rows = [row["_source"] for row in resp["hits"]["hits"]]

    # We want to return the group the data by board number

    # so that we can score each board.                                                                       

    keyfunc = lambda row: int(row['board_number'])                                                                               

    rows.sort(key=keyfunc)                                                                                                       

    for _, group in itertools.groupby(rows, keyfunc):                                                                            

        yield list(group)


def compute_mp(scores, score):

    """Compute the match point score for a pair."""

    mp_score = sum(v for k, v in scores.items() if score > k) * 2

    # The pair's own score will always compare equal - remove it.

    mp_score += sum(v for k, v in scores.items() if score == k) - 1

    return mp_score


def score_board(tables):

    """Build the scores for each pair."""

    scores = []

    top = 2 * (len(tables) - 1)

    # Store the scores for each N-S partnership.

    ns_scores = collections.Counter(int(table["nsscore"]) for table in tables)

    # Build the output for each pair.


与以前一样,它会产生正确的字典,其中评分正确,但结果重复且行数过多。


胡子哥哥
浏览 191回答 2
2回答

函数式编程

此代码将计算分数。代码相当简单。不是遍历输入字典来计算每对的分数,而是将南北分数存储在collections.Counter实例中,该实例记录了产生每个分数的对数。这使得计算每一对的赛点得分变得更容易——我们只是将得分较低的数量加倍,并将得分相等的数量相加,减去一个以计算当前伙伴关系的得分。import collections                                                                                                               import itertools                                                                                                                                                                                                                                    def extract_rows(resp):                                                                                                              """Extract the rows for the board from the query response."""                                                                    # Based on the data structure provided by the OP.                                                              rows = [row["_source"] for row in resp["hits"]["hits"]]    # We want to return the group the data by board number    # so that we can score each board.                                                                           keyfunc = lambda row: int(row['board_number'])                                                                                   rows.sort(key=keyfunc)                                                                                                           for _, group in itertools.groupby(rows, keyfunc):                                                                                    yield list(group)def compute_mp(scores, score):    """Compute the match point score for a pair."""    mp_score = sum(v for k, v in scores.items() if score > k) * 2    # The pair's own score will always compare equal - remove it.    mp_score += sum(v for k, v in scores.items() if score == k) - 1    return mp_scoredef score_board(tables):    """Build the scores for each pair."""    scores = []    # Store the scores for each N-S partnership.    ns_scores = collections.Counter(int(table["nsscore"]) for table in tables)    # The top score is (2 * number of tables) - 2, then reduced by one for each     # equal top score.    top = 2 * (len(tables) - 1) - (ns_scores[max(ns_scores)] - 1)    # Build the output for each pair.    for table in tables:        output = {            "board": table["board_number"],            "nsp": table["nsp"],            "ewp": table["ewp"],        }        ns_score = int(table["nsscore"])        ns_mp_score = compute_mp(ns_scores, ns_score)        output["ns_mp_score"] = ns_mp_score        ew_mp_score = top - ns_mp_score        output["ew_mp_score"] = ew_mp_score        scores.append(output)    return scores# Replace this function with one that adds the rows to# the new search indexdef report(scores):    """Print the scores."""    for row in scores:        print(row)运行代码:rows = extract_rows(resp)scores = [score for rows in extract_rows(resp) for score in score_board(rows)]report(scores)产生这个输出:{'board': '1', 'nsp': '4', 'ewp': '11', 'ns_mp_score': 6, 'ew_mp_score': 2}{'board': '1', 'nsp': '5', 'ewp': '12', 'ns_mp_score': 2, 'ew_mp_score': 6}{'board': '1', 'nsp': '1', 'ewp': '16', 'ns_mp_score': 4, 'ew_mp_score': 4}{'board': '1', 'nsp': '6', 'ewp': '13', 'ns_mp_score': 8, 'ew_mp_score': 0}{'board': '1', 'nsp': '7', 'ewp': '14', 'ns_mp_score': 0, 'ew_mp_score': 8}{'board': '2', 'nsp': '3', 'ewp': '10', 'ns_mp_score': 4, 'ew_mp_score': 4}{'board': '2', 'nsp': '7', 'ewp': '14', 'ns_mp_score': 4, 'ew_mp_score': 4}{'board': '2', 'nsp': '8', 'ewp': '15', 'ns_mp_score': 0, 'ew_mp_score': 8}{'board': '2', 'nsp': '1', 'ewp': '16', 'ns_mp_score': 8, 'ew_mp_score': 0}{'board': '2', 'nsp': '2', 'ewp': '9', 'ns_mp_score': 4, 'ew_mp_score': 4}

慕少森

这不是我的工作,它是“rvs”的工作,但由于这是我正在寻找的答案,因此我会将其发布在这里,以便对其他人有所帮助。scores = {}for row in arr["hits"]["hits"]:&nbsp; nsp = row["_source"]["nsp"]&nbsp; nsscore = row["_source"]["nsscore"]&nbsp; scores[nsp] = nsscoreinput_scores = {}def calculate_score(pair, scores):&nbsp; &nbsp; score = 0&nbsp; &nbsp; for p in scores:&nbsp; &nbsp; &nbsp; &nbsp; if p == pair:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; if scores[p] < scores[pair]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; score += 2&nbsp; # win&nbsp; &nbsp; &nbsp; &nbsp; elif scores[p] == scores[pair]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; score += 1&nbsp; &nbsp; return scoreboard_num = arr["hits"]["total"]top = (board_num - 1) * 2result_score = {}for row in arr["hits"]["hits"]:&nbsp; nsp = row["_source"]["nsp"]&nbsp; ewp = row["_source"]["ewp"]&nbsp; res = calculate_score(nsp, scores)&nbsp; ew_mp_score = top - res&nbsp; result_score.update({'nsp':nsp, 'ns_mp_score': res, 'ewp': ewp, 'ew_mp_score': ew_mp_score})&nbsp; print(result_score)谢谢你。
随时随地看视频慕课网APP

相关分类

Python
我要回答