用于打印格式化嵌套列表的Python lambda

用于打印格式化嵌套列表的Python lambda,python,string,list,lambda,Python,String,List,Lambda,练习两件事: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

练习两件事: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()])
请注意,我们可以直接将字符串传递到
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(' ')])
你想要这个:

' '.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

第一种句子处理方法的改进版本:

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