web-dev-qa-db-ja.com

Python:配列v。リスト

可能性のある複製:
Pythonリストと配列-いつ使用するか?

Pythonでいくつかのプロジェクトに取り組んでいますが、いくつか質問があります。

  1. 配列とリストの違いは何ですか?
  2. 質問1から明らかでない場合、どちらを使用すればよいですか?
  3. 優先するものをどのように使用しますか? (配列/リストの作成、アイテムの追加、アイテムの削除、ランダムなアイテムの選択)
29
tkbx

C配列ライブラリにある非常に特殊な機能が必要な場合を除き、リストを使用します。

pythonには本当に3つのプリミティブなデータ構造があります

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.

データ構造の詳細はこちら: http://docs.python.org/tutorial/datastructures.html

39
Matt Alcock

ここでは特に具体的なことはなく、この答えは少し主観的です...

一般に、構文でサポートされており、他のライブラリなどでより広く使用されているという理由だけで、リストを使用する必要があると感じています。

「リスト」内のすべてが同じタイプであることがわかっており、データをよりコンパクトに保存する場合は、 arrays を使用する必要があります。

14
Donald Miner