Come passare dalla lista di parole da un elenco di lettere distinte in Python
-
20-09-2019 - |
Domanda
Usare Python, sto cercando di convertire una frase di parole in una semplice lista di tutte le lettere distinte in quella frase.
Ecco il mio codice corrente:
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
Questo codice restituisce ['s', 'h', 'e', 'l', 'a', 'b', 'y', 't', 'o', 'r']
, che è corretto, ma c'è un modo più Pythonic a questa risposta, probabilmente utilizzando list comprehensions / set
?
Quando cerco di coniugare lista-di comprensione e filtraggio di nidificazione, ottengo gli elenchi delle liste, invece di una semplice lista.
L'ordine delle lettere distinte nella lista finale (ltr
) non è importante; ciò che è importante è che siano unici.
Soluzione
Set forniscono una soluzione semplice, efficace.
words = 'She sells seashells by the seashore'
unique_letters = set(words.lower())
unique_letters.discard(' ') # If there was a space, remove it.
Altri suggerimenti
Fare ltr
un insieme e cambiare il vostro corpo del ciclo un po ':
ltr = set()
for word in word_list:
for c in word:
ltr.add(c)
o utilizzando una lista di comprensione:
ltr = set([c for word in word_list for c in word])
set([letter.lower() for letter in words if letter != ' '])
Modifica : Ho appena provato e trovato questo sarà anche funziona (forse questo è ciò che si riferiva a SilentGhost):
set(letter.lower() for letter in words if letter != ' ')
E se è necessario disporre di un elenco piuttosto che un insieme, puoi
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'])
qui ci sono alcuni tempi fatti con 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