[英]How to go from list of words to a list of distinct letters in 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方式来回答这个问题,可能是使用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.
set([letter.lower() for letter in words if letter != ' '])
编辑 :我刚刚尝试过,发现这也有效(也许这就是SilentGhost所指的):
set(letter.lower() for letter in words if letter != ' ')
如果你需要一个列表而不是一个集合,你可以
list(set(letter.lower() for letter in words if letter != ' '))
使ltr
成为一组并稍微改变你的循环体:
ltr = set()
for word in word_list:
for c in word:
ltr.add(c)
或者使用列表理解:
ltr = set([c for word in word_list for c in word])
>>> set('She sells seashells by the seashore'.replace(' ', '').lower()) set(['a', 'b', 'e', 'h', 'l', 'o', 's', 'r', 't', 'y']) >>> set(c.lower() for c in 'She sells seashells by the seashore' if not c.isspace()) set(['a', 'b', 'e', 'h', 'l', 'o', 's', 'r', 't', 'y']) >>> from itertools import chain >>> set(chain(*'She sells seashells by the seashore'.lower().split())) set(['a', 'b', 'e', 'h', 'l', 'o', 's', 'r', 't', 'y'])
这里是py3k的一些时间:
>>> import timeit
>>> def t(): # mine (see history)
a = {i.lower() for i in words}
a.discard(' ')
return a
>>> timeit.timeit(t)
7.993071812372081
>>> def b(): # danben
return set(letter.lower() for letter in words if letter != ' ')
>>> timeit.timeit(b)
9.982847967921138
>>> def c(): # ephemient in comment
return {i.lower() for i in words if i != ' '}
>>> timeit.timeit(c)
8.241267610375516
>>> def d(): #Mike Graham
a = set(words.lower())
a.discard(' ')
return a
>>> timeit.timeit(d)
2.7693045186082372
set(l for w in word_list for l in w)
words = 'She sells seashells by the seashore'
ltr = list(set(list(words.lower())))
ltr.remove(' ')
print ltr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.