2012-02-23 14 views
21

Duplicar posibles:
Python List vs. Array - when to use?Python:. V matriz Lista

estoy trabajando en algunos proyectos en Python, y tengo algunas preguntas:

  1. ¿Cuál es la diferencia entre matrices y listas?
  2. Si no es obvio desde la pregunta 1, ¿qué debería usar?
  3. ¿Cómo se usa el preferido? (Crear matriz/lista, añade el artículo, retire artículo, recoger artículo al azar)
+1

Esto se siente más como una petición tutorial en lugar de una pregunta sin embargo ver mis notas abajo. Por favor vota y/o acepta si es necesario –

Respuesta

32

Use listas a menos que desee algunas características muy específicas que se encuentran en las bibliotecas de arreglos C.

pitón realmente tiene tres estructuras de datos primitivos

tuple = ('a','b','c') 
list = ['a','b','c'] 
dict = {'a':1, 'b': true, 'c': "name"} 

list.append('d') #will add 'd' to the list 
list[0] #will get the first item 'a' 

list.insert(i, x) # Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).  

list.pop(2) # will remove items by position (index), remove the 3rd item 
list.remove(x) # Remove the first item from the list whose value is x. 

list.index(x) # Return the index in the list of the first item whose value is x. It is an error if there is no such item. 

list.count(x) # Return the number of times x appears in the list. 

list.sort(cmp=None, key=None, reverse=False) # Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation). 

list.reverse() # Reverse the elements of the list, in place. 

Más sobre estructuras de datos aquí: http://docs.python.org/tutorial/datastructures.html

+9

no te olvides de los conjuntos ... – wim

+0

correctos también hay conjuntos. colecciones sin elementos repetitivos. http://docs.python.org/tutorial/datastructures.html#sets –

10

En realidad nada concreto aquí y esta respuesta es un poco subjetivo ...

En general, siento que debe utilizar una lista solo porque es compatible con la sintaxis y se usa más ampliamente en otras bibliotecas, etc.

Debe usar arrays si sabe que todo en la "lista" será del mismo tipo y desea almacenar el datos de forma más compacta.