簡體   English   中英

pythonic句子中的反詞

[英]reverse words in a sentence pythonic

我正在嘗試編寫pythonic代碼以反轉句子中的單詞

例如:

input: "hello there friend"

output: "friend there hello"

碼:

class Solution:
    def swap(self, w):
        return w[::-1]

    def reverseWords(self, s):
        w = self.swap(s).split()
        return ' '.join(for x in w: swap(x))

使它無法正常工作有點麻煩。 我需要有關退貨單的幫助

您以錯誤的順序調用交換/拆分。 使用此代替:

w = self.swap(s.split())

然后,您的申報表不需要做任何理解:

return ' '.join(w)

雖然將其包裝在類中並沒有很多錯誤,但這並不是最Python化的處理方式。 這是您要執行的操作的簡短版本:

def reverse(sentence):
    return ' '.join(sentence.split()[::-1])

輸出:

In [29]: reverse("hello there friend")
Out[29]: 'friend there hello'

另一個

def revereString(orgString):
  result = []
  splittedWords = orgString.split(" ")
  for item in range(len(splittedWords)-1, -1, -1):
    result.append(splittedWords[item])
  return result

print(revereString('Hey ho hay'))

暫無
暫無

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

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