出于好奇:创造总和哪个更好?总和(列表)与积累

时间:2014-11-24 01:45:22

标签: python list concatenation

我正在计算一条路线的总距离(对于一个旅行商问题),我很好奇哪个更好:总结一个整数列表,或者使用总+ =值(不确定这个的技术术语是什么) ..串联我相信吗?)。换句话说:

totalDistance = [distance(location, location+1) for location in route]
return sum(totalDistance)

totalDistance = 0
for location in route:
    totalDistance += distance(location, location+1)
return totalDistance

distance()返回int值,不同路径的位置数在0到100之间变化。 对任何一种方法(或完全不同的方式)的想法都很感激!

编辑:

累积,而不是连接。

3 个答案:

答案 0 :(得分:2)

为什么不将generator expressionsum

一起使用
return sum(distance(location, location+1) for location in route)

此解决方案避免了像第一个解决方案那样创建不必要的列表(节省内存消耗),并且比第二个更清晰(清洁度计数)。

那就是说,你总是可以将第一个解决方案合并为一个单行:

return sum([distance(location, location+1) for location in route])

但是,正如我上面所说,为什么创建一个列表只是为了扔掉它?

答案 1 :(得分:1)

最好只使用sum

的生成器表达式
return sum(distance(location, location+1) for location in route)

这节省了创建列表的开销。 totalDistance = [路线中位置的距离(位置,位置+ 1)]

for循环版本也不会创建列表。这很好,与使用sum相比,只是有点冗长。 sum恰好适用于此类案例

location+1如何运作?好像它应该是路线的下一个项目


为了兴趣,我比较了PyPy 2.2.1中的@iCodez示例。每个函数的第一次运行是允许JIT编译函数

>>>> from timeit import timeit
>>>> def f():
....     number = 0
....     for i in range(100):
....         number += 1
.... 
>>>> timeit(f)
0.3245859146118164
>>>> timeit(f)
0.2913198471069336

>>>> def g():
....     lst = [i for i in range(100)]
....     sum(lst)
.... 
>>>> timeit(g)
0.8840188980102539
>>>> timeit(g)
0.8698201179504395

>>>> def h():
....     sum(i for i in range(100))
.... 
>>>> timeit(h)
2.8281970024108887
>>>> timeit(h)
2.8702847957611084

Wow..genexp表现更差

答案 2 :(得分:0)

在我的机器上,迭代生成器比列表慢:

from timeit import timeit

# just for simulation
def distance(la, lb):
    return abs(la-lb)

# for simulation, too    
def route():
    return xrange(10000)

# the longer(code) and faster but wasteful(memory) way
def longer_faster_wasteful():
    return sum([distance(location, location+1) for location in route()])

# the shorter(code) and saving(memory) but slower way
def shorter_slower_saving():
    return sum(distance(location, location+1) for location in route())

# print 2.01163072818 on my machine
print timeit(longer_faster_wasteful, number=100)

# print 2.91834802689 on my machine
print timeit(shorter_slower_saving, number=100)