Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
Agregue solo valores únicos a una lista en python

Estoy tratando de aprender Python. Aquí está la parte relevante del ejercicio:

Para cada palabra, verifique si la palabra ya está en una lista. Si la palabra no está en la lista, agréguela a la lista.

Esto es lo que tengo.

 fhand = open('romeo.txt') output = [] for line in fhand: words = line.split() for word in words: if word is not output: output.append(word) print sorted(output)

Esto es lo que obtengo.

 ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'is', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun', 'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder']

Nota duplicación (y, es, sol, etc).

¿Cómo obtengo solo valores únicos?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Para eliminar duplicados de una lista, puede mantener una lista auxiliar y verificarla.

 myList = ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'is', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun', 'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder'] auxiliaryList = [] for word in myList: if word not in auxiliaryList: auxiliaryList.append(word)

producción:

 ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

Esto es muy simple de comprender y el código se explica por sí mismo. Sin embargo, la simplicidad del código se produce a expensas de la eficiencia del código, ya que los escaneos lineales sobre una lista en crecimiento hacen que un algoritmo lineal se degrade a cuadrático.


Si el orden no es importante, puede usar set()

Un objeto conjunto es una colección desordenada de distintos objetos hashable.

Hashability hace que un objeto se pueda usar como una clave de diccionario y un miembro del conjunto, porque estas estructuras de datos usan el valor hash internamente.

Dado que el caso promedio para la verificación de membresía en una tabla hash es O (1), usar un conjunto es más eficiente.

 auxiliaryList = list(set(myList))

producción:

 ['and', 'envious', 'already', 'fair', 'is', 'through', 'pale', 'yonder', 'what', 'sun', 'Who', 'But', 'moon', 'window', 'sick', 'east', 'breaks', 'grief', 'with', 'light', 'It', 'Arise', 'kill', 'the', 'soft', 'Juliet']
over 4 years ago · Santiago Trujillo Report

0

En lugar del operador is not , debe usar el operador not in para verificar si el elemento está en la lista:

 if word not in output:

Por cierto, usar set es muy eficiente (ver Complejidad del tiempo ):

 with open('romeo.txt') as fhand: output = set() for line in fhand: words = line.split() output.update(words)

ACTUALIZACIÓN El set no conserva el orden original. Para conservar el orden, utilice el conjunto como estructura de datos auxiliar:

 output = [] seen = set() with open('romeo.txt') as fhand: for line in fhand: words = line.split() for word in words: if word not in seen: # faster than `word not in output` seen.add(word) output.append(word)
over 4 years ago · Santiago Trujillo Report

0

Un método es ver si está en la lista antes de agregar, que es lo que hace la respuesta de Tony. Si desea eliminar valores duplicados después de crear la lista, puede usar set() para convertir la lista existente en un conjunto de valores únicos y luego usar list() para convertirla en una lista nuevamente. Todo en una sola línea:

 list(set(output))

Si desea ordenar alfabéticamente, simplemente agregue sorted() a lo anterior. Aquí está el resultado:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!