python中对list元素求和、求积的普通方法和便捷方法

python中对list元素求和、求积的普通方法和便捷方法

1.单个list

求和、求积最先想到的是for循环,可以直接使用python中封装的函数,一行代码解决问题,一般来说,能不用for循环就不用,因为相比于封装函数,for循环太慢。

# -*- encoding:utf-8 -*-
from pandas.compat import reduce
 
a = [1, 2, 3, 4, 5, 6]
#遍历
s = 0
for x in a:
    s += x
print('first sum value : ', s)
#直接sum
s = sum(a)
print('second sum value : ', s)
# 输出 :
# first sum value :  21
# second sum value :  21
#求积,遍历
s = 1
for x in a:
    s *= x
print('first dot value : ', s)
#求积,算子
from operator import mul
reduce(mul, a)
print('second dot value : ', s)
# 输出:
# first dot value :  720
# second dot value :  720

举个例子,看看for循环花费的时间,相比于封装的函数,慢了一个量级。

# -*- encoding:utf-8 -*-
from pandas.compat import reduce
import time
#遍历
s = 0
s1= time.time()
for x in range(10000):
    s += x
print('time cost :', time.time() - s1)
print('first sum value : ', s)
 
#直接sum
s2 = time.time()
s = sum(range(10000))
print('time cost :', time.time() - s2)
print('second sum value : ', s)
# 输出 :
time cost : 0.001344919204711914
first sum value :  49995000
time cost : 0.00023603439331054688
second sum value :  49995000

2.两个list

    f = [0.3010029,0.020573696,-0.027781123,0.030090092,-0.27083227,-0.37045234,0.009237794,-0.11004987,0.063552536,-0.005491335,0.11150571,0.16549589,0.15243669,-0.055794537,0.061482713,0.09465289,-0.016916709,0.2489126,-0.12095779,0.024866233,-0.11458805,-0.3941095,-0.08246311,-0.074405506,0.029491333,-0.16940126,0.03623533,0.11114747,-0.41313538,-0.16460033,-0.27770418,0.15851085]
    u = [0.1924674,-0.06826515,0.21713683,0.20187074,0.19647224,-0.10442781,-0.1260283,-0.053464226,-0.23348433,0.13501461,0.0010000418,0.17120077,0.33510914,-0.25059026,0.16857275,0.12789226,0.09749177,-0.089784734,-0.088397115,-0.16015747,0.08469256,-0.092553146,0.3440129,-0.2014734,-0.18734993,0.018540349,0.018551964,-0.18629988,0.1415954,0.22330056,-0.29975843,0.15574892]
    res = [a*b for a,b in zip(f, u)]
    print(res)
    s_res = sum(res)
    print(s_res)

参考 https://blog.csdn.net/pearl8899/article/details/109481321?op

您可能还喜欢...

发表回复