Python:数组v.Lis

2024-04-26 05:21:18 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Python List vs. Array - when to use?

我正在用Python开发一些项目,我有几个问题:

  1. 数组和列表有什么区别?
  2. 如果从问题1看不明显,我应该用哪一个?
  3. 你怎么用首选的?(创建数组/列表、添加项、移除项、选择随机项)

Tags: to项目列表use数组arraylistvs
2条回答

使用列表,除非您需要C数组库中的一些非常特定的功能。

python实际上有三个基本的数据结构

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

这里没有什么具体的东西,这个答案有点主观。。。

一般来说,我觉得您应该使用列表,因为它在语法中受支持,在其他库中使用得更广泛,等等

如果您知道“list”中的所有内容都是同一类型,并且希望更紧凑地存储数据,那么应该使用arrays

相关问题 更多 >