如何在 Python 中从单词列表转为不同字母列表
使用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的方式,可能使用列表理解/set
?
当我尝试结合列表理解嵌套和过滤时,我得到的是列表列表而不是平面列表。
最终列表 (ltr
) 中不同字母的顺序并不重要;重要的是它们是独一无二的。
Using Python, I'm trying to convert a sentence of words into a flat list of all distinct letters in that sentence.
Here's my current code:
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
This code returns ['s', 'h', 'e', 'l', 'a', 'b', 'y', 't', 'o', 'r']
, which is correct, but is there a more Pythonic way to this answer, probably using list comprehensions/set
?
When I try to combine list-comprehension nesting and filtering, I get lists of lists instead of a flat list.
The order of the distinct letters in the final list (ltr
) is not important; what's crucial is that they be unique.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
集合提供了简单、高效的解决方案。
Sets provide a simple, efficient solution.
使
ltr
成为一个集合并稍微更改循环体:或者使用列表理解:
Make
ltr
a set and change your loop body a little:Or using a list comprehension:
编辑:我刚刚尝试过,发现这也可以工作(也许这就是SilentGhost所指的):
如果你需要一个列表而不是一组,你可以
Edit: I just tried it and found this will also work (maybe this is what SilentGhost was referring to):
And if you need to have a list rather than a set, you can
以下是使用 py3k 进行的一些计时:
here are some timings made with py3k: