簡體   English   中英

Python函數返回空列表

[英]Python function returns empty list

我已經在這項任務上工作了一段時間,任務是編寫一個將英文文本翻譯成瑞典語的函數。 我創建了一個帶鍵和值的dicitonary,其中key是英文單詞,value是瑞典單詞。

我是如何思考的:我在考慮應該有2個for循環。 第一個應該通過字典中的鍵和值迭代,第二個應該通過字符串迭代,之后應該有一個條件,它檢查字典中的鍵是否等於字符串中的單詞。 如果是這樣,請將鍵的值附加到列表中。

問題 :該函數返回一個空列表。

這是我的代碼

def translate(a):
    trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
    translated = []
    for k, v in trs.iteritems():
        for i in a.split(" "): 
            if trs[k] == i:
                translated.append(trs[v])
    return translated

print translate("merry christmas and happy new year")

您的代碼存在多個問題。

第一個是你迭代字典中的鍵值對,然后嘗試在這里使用值作為鍵: if trs[k] == i: and here translated.append(trs[v])這些應該只是kv而不是trs[k]trs[v]

第二個問題是一個更大的問題:修復前一個問題后,代碼仍然給出了錯誤的答案。 這些詞是隨機順序的。 這是因為您遍歷外部循環中的字典項而不是單詞本身。 通過改變循環的順序可以很容易地解決這個問題。

第三是我認為函數應該返回一個字符串。 最后只返回" ".join(translated)

第四是你實際上不使用字典作為字典。 您將它用作列表,但不是它們的使用方式。 dict是值的直接映射,您不需要一直迭代所有條目。 使用in[]運算符。

所以這是這個代碼應該是這樣的:

def translate(a):
    trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ar"}
    translated = []
    for i in a.split(" "): 
      if i in trs:
        translated.append(trs[i])
    return " ".join(translated)

print translate("merry christmas and happy new year")
# prints "god jul och gott nytt ar"
  • 您希望在翻譯中保留單詞順序,這意味着對原始單詞的迭代應該驅動算法(而不是對翻譯詞典進行迭代)。

  • 無需迭代字典:鍵值數據結構的目的是允許您通過鍵快速檢索單個項目。

  • 字典有一個get()方法,在密鑰可能存在或不存在的情況下很方便。

  • 只是猜測,但似乎該方法應該返回文本而不是翻譯單詞列表(相應地調整)。

  • 所以這一切歸結為:

     return ' '.join(trs.get(w, w) for w in orig_text.split()) 

我認為這就是你要找的東西:

trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
translated = []
for i in a.split(" "):  # loop over sentence and try to translate every word
    if i in trs:  # the word to be translated is a key in your dict
        translated.append(trs[i])  # add the translation if present
    # else
    #   translated.append(i)
return ' '.join(translated)  # makes more sense than returning a list
def translate(a):
    trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ar"}
    translated = []
    for i in a.split(" "):
        for k, v in trs.iteritems():
            if i == k:
                translated.append(trs[i])
    return translated

print translate("merry christmas and happy new year")

# output:
# ['god', 'jul', 'och', 'gott', 'nytt', 'ar']
def translate(a):
    trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
    translated = []
    for i in a.split(" "):
        for k, v in trs.iteritems():
            if k == i:
                translated.append(trs[k])
return translated

print translate("merry christmas and happy new year)

在第6行中,您正在執行trs [k],它將在trs [k]處返回值,該值不等於任何子字符串。 這就是為什么你得到一個空列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM