[英]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.