如何从单词列表到Python中的不同字母列表
发布时间:2020-12-20 13:02:57 所属栏目:Python 来源:网络整理
导读:使用 Python,我试图将一个单词的句子转换成该句子中所有不同字母的平面列表. 这是我目前的代码: words = 'She sells seashells by the seashore'ltr = []# Convert the string that is "words" to a list of its component wordsword_list = [x.strip().low
使用
Python,我试图将一个单词的句子转换成该句子中所有不同字母的平面列表.
这是我目前的代码: words = 'She sells seashells by the seashore' ltr = [] # Convert the string that is "words" to a list of its component words word_list = [x.strip().lower() for x in words.split(' ')] # Now convert the list of component words to a distinct list of # all letters encountered. for word in word_list: for c in word: if c not in ltr: ltr.append(c) print ltr 这段代码返回[‘s’,’h’,’e’,’l’,’a’,’b’,’y’,’t’,’o’,’r’],这是正确的,但是是否有更多的Pythonic方式来回答这个问题,可能是使用list comprehensions / set? 当我尝试组合列表理解嵌套和过滤时,我得到列表而不是平面列表. 最终列表(ltr)中不同字母的顺序并不重要;至关重要的是它们是独一无二的. 解决方法
集合提供简单,有效的解决方案.
words = 'She sells seashells by the seashore' unique_letters = set(words.lower()) unique_letters.discard(' ') # If there was a space,remove it. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |