2012-02-23 17 views
21

Eventuali duplicati:
Python List vs. Array - when to use?Python:. Array v Lista

Sto lavorando su alcuni progetti in Python, e ho un paio di domande:

  1. Qual è la differenza tra array ed elenchi?
  2. Se non è ovvio dalla domanda 1, quale dovrei usare?
  3. Come si usa quello preferito? (Creare un array/lista, aggiungere voce, togliere voce, raccogliere elemento casuale)
+1

Questa sembra più una richiesta di un'esercitazione piuttosto che una domanda però vedere le mie note qui sotto. Si prega di votare e/o accettare, se del caso, –

risposta

32

Utilizzare gli elenchi a meno che non desideriate alcune funzionalità molto specifiche contenute nelle librerie di array C.

pitone ha davvero tre strutture di dati primitivi

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. 

Maggiori info su strutture dati qui: http://docs.python.org/tutorial/datastructures.html

+9

non dimenticare set .. – wim

+0

corretto ci sono anche set. collezioni senza elementi ripetitivi. http://docs.python.org/tutorial/datastructures.html#sets –

10

Niente di veramente concreto qui e questa risposta è un po 'soggettivo ...

In generale, mi sento si dovrebbe usare una lista solo perché è supportata nella sintassi e viene utilizzato più ampiamente nelle altre biblioteche, ecc

si dovrebbe usare arrays se si sa che tutto nella "lista" sarà dello stesso tipo e si desidera memorizzare il dati più compatti.