我的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)
添加回答
舉報
0/150
提交
取消