簡體   English   中英

Python Lambda打印格式化的嵌套列表

[英]Python lambda to print formatted nested list

練習一些事情:lambda函數和字符串操作。 我想找到最有效的方法而不導入任何東西。

因此,這是一個簡短的腳本,可按字母順序重新排列單詞:

def alphabeticalOrder(word):
    lst = [l for l in word]
    return sorted(lst)


def main ():
    word = raw_input('enter word: ')
    print "".join(alphabeticalOrder(word))


if __name__ == '__main__':
    main()

我想對句子中的所有單詞執行此操作:

def alphabeticalOrder(line):
    lst = []
    for word in line.split(" "):
        lst.append(sorted(list(word)))
    print lst     # trouble here

def main ():
        line = raw_input('enter sentence: ')
        print alphabeticalOrder(line)

if __name__ == '__main__':
    main()

所以我的問題是; 您能否編寫一個lambda函數來遍歷lst中的嵌套列表,該函數將每個項目打印為只是一串按字母順序排序的單詞?

列表推導要容易得多:

' '.join([''.join(sorted(word)) for word in sentence.split()])

請注意,我們可以將字符串直接傳遞給sorted()

Lambda只是具有單個表達式的函數,可以將其定義為表達式本身。 在這里,我首先將lambda結果分配給變量:

alphabeticalWord = lambda w: ''.join(sorted(word))

' '.join([alphabeticalWord(word) for word in sentence.split()])

你要這個:

' '.join([''.join(sorted(word)) for word in sentence.split(' ')])

第一種用於句子的工作方法的改進版本:

def alphabeticalOrder(word):
    return "".join(sorted(lst)) #return the sorted string


def main ():
    sent = raw_input('enter sentence: ')
    print " ".join(map(alphabeticalOrder,sent.split())) #map alphabeticalOrder to each
                                                        #word in the sentence


if __name__ == '__main__':
    main()

輸出:

enter sentence: foo bar spam eggs
foo abr amps eggs

暫無
暫無

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

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