使用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) 并不重要;重要的是它们是独一无二的。

有帮助吗?

解决方案

集合提供了简单、高效的解决方案。

words = 'She sells seashells by the seashore'

unique_letters = set(words.lower())
unique_letters.discard(' ') # If there was a space, remove it.

其他提示

制作 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([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 != ' '))
>>> 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归因
不隶属于 StackOverflow
scroll top