Python 列表索引还是追加?

Python List Indexing or Appending?

在处理时间、内存使用方面,将值添加到 List 的最佳方法是什么,一般而言,最佳编程选项是什么。

list = []

for i in anotherArray:
    list.append(i)

list = range(len(anotherArray))

for i in list:
    list[i] = anotherArray[i]

考虑到 anotherArray 例如是一个元组数组。 (这只是一个简单的例子)

最好的方法是列表理解:

my_list=[i for i in anotherArray]

但是根据您的问题,您可以使用生成器表达式(当您只想循环遍历您的项目并且不需要使用某些列表方法(如 indexinglen 或...)

my_list=(i for i in anotherArray)

我实际上会说最好的是 index loopsvalue loops 与枚举的组合:

for i, j in enumerate(list): # i is the index, j is the value, can't go wrong

这真的取决于您的用例。这里没有通用的答案,因为这取决于您要做什么。

在您的示例中,您似乎只是在尝试创建数组的副本,在这种情况下,最好的方法是使用 copy:

from copy import copy    
list = copy(anotherArray)

如果您尝试将数组转换为另一个数组,您应该使用列表理解。

list =  [i[0] for i in anotherArray]  # get the first item from tuples in anotherArray

如果你想同时使用索引和对象,你应该使用枚举:

for i, j in enumerate(list)

这比你的第二个例子好多了。

您还可以使用生成器、lambas、映射、过滤器等。所有这些可能性存在的原因是因为它们都是 "better" 出于不同的原因。 python 的作者在 "one right way" 上非常重要,所以请相信我,如果有一种通用的方法总是更好,那就是 python 中唯一存在的方法。


编辑:运行 元组交换的一些性能结果,结果如下:

comprehension: 2.682028295999771
enumerate: 5.359116118001111
for in append: 4.177091988000029
for in indexes: 4.612594166001145

如您所知,理解通常是最好的选择。使用枚举很昂贵。 这是上述测试的代码:

from timeit import timeit

some_array = [(i, 'a', True) for i in range(0,100000)]

def use_comprehension():
    return [(b, a, i) for i, a, b in some_array]

def use_enumerate():
    lst = []
    for j, k in enumerate(some_array):
        i, a, b = k
        lst.append((b, a, i))
    return lst

def use_for_in_with_append():
    lst = []
    for i in some_array:
        i, a, b = i
        lst.append((b, a, i))
    return lst

def use_for_in_with_indexes():
    lst = [None] * len(some_array)
    for j in range(len(some_array)):
        i, a, b = some_array[j]
        lst[j] = (b, a, i)
    return lst

print('comprehension:', timeit(use_comprehension, number=200))
print('enumerate:', timeit(use_enumerate, number=200))
print('for in append:', timeit(use_for_in_with_append, number=200))
print('for in indexes:', timeit(use_for_in_with_indexes, number=200))

编辑2:

有人向我指出,OP 只是想知道 "indexing" 和 "appending" 之间的区别。实际上,它们也用于两个不同的用例。索引用于替换对象,而附加用于添加。但是,在列表开始为空的情况下,附加总是会更好,因为索引具有最初创建列表的开销。从上面的结果可以看出,索引速度稍慢,主要是因为你必须创建第一个列表。