亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python嵌套的生成器對象內容

python嵌套的生成器對象內容

Helenr 2021-03-14 16:17:43
我的Python有問題。我試圖了解哪些信息存儲在我發現是生成器的對象中。我對Python一無所知,但是我必須了解這段代碼的工作原理才能將其轉換為Java。代碼如下:def segment(text):    "Return a list of words that is the best segmentation of text."    if not text: return []    candidates = ([first]+segment(rem) for first,rem in splits(text))    return max(candidates, key=Pwords)def splits(text, L=20):    "Return a list of all possible (first, rem) pairs, len(first)<=L."    pairs = [(text[:i+1], text[i+1:]) for i in range(min(len(text), L))]    return pairsdef Pwords(words):     "The Naive Bayes probability of a sequence of words."    productw = 1    for w in words:      productw = productw * Pw(w)    return productw雖然我了解了Pwords和split方法的工作原理(函數Pw(w)只是從矩陣中獲取一個值),但我仍在嘗試了解“ segment”方法中“ candidates”對象的構建方式,以及它包含。以及“ max()”函數如何分析此對象。我希望有人能幫助我,因為我在這里找不到任何可行的解決方案來打印此對象。非常感謝大家。毛羅
查看完整描述

1 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

生成器是相當簡單的抽象。它看起來像一次性使用的自定義迭代器。


gen = (f(x) for x in data)

表示gen是迭代器,每個下一個值等于f(x),其中x是數據的對應值


嵌套生成器類似于列表推導,但有很小的區別:


它是一次性的

它不會創建整個序列

代碼僅在迭代期間運行

為了更容易調試,您可以嘗試用列表理解替換嵌套生成器


def segment(text):

    "Return a list of words that is the best segmentation of text."

    if not text: return []

    candidates = [[first]+segment(rem) for first,rem in splits(text)]

    return max(candidates, key=Pwords)


查看完整回答
反對 回復 2021-03-24
  • 1 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號