Python:数组v.列表[重复]

Posted

技术标签:

【中文标题】Python:数组v.列表[重复]【英文标题】:Python: Array v. List [duplicate] 【发布时间】:2012-03-13 09:39:10 【问题描述】:

可能重复:Python List vs. Array - when to use?

我正在使用 Python 进行一些项目,我有几个问题:

    数组和列表有什么区别? 如果问题 1 不明显,我应该使用哪个? 如何使用首选的? (创建数组/列表、添加项目、删除项目、选择随机项目)

【问题讨论】:

这感觉更像是一个教程请求而不是一个问题,但是请参阅下面的注释。如果合适,请投票和/或接受 【参考方案1】:

除非您想要 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

【讨论】:

别忘了套.. 正确也有套。没有重复项目的集合。 docs.python.org/tutorial/datastructures.html#sets【参考方案2】:

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

总的来说,我觉得你应该使用列表,因为它在语法上受支持,并且在其他库等中使用更广泛。

如果您知道“列表”中的所有内容都属于同一类型并且您希望更紧凑地存储数据,则应该使用arrays。

【讨论】:

以上是关于Python:数组v.列表[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Python - 如何创建一个空的numpy数组并附加到它,如列表[重复]

如何将所有数组的元素添加到python中的一个列表中[重复]

如何在python列表数组中找到大值的位置[重复]

如何将各种尺寸的数组的Python列表保存到mat文件[重复]

typescript K:来自字符串列表的V.

python找出列表元素重复个数和重复值