Python 迭代两个列表中的每个值,然后将它们放入公式中
下面是我的数据演示Python 迭代两个列表中的每个值,然后将它们放入公式中,python,python-3.x,for-loop,Python,Python 3.x,For Loop,下面是我的数据演示 a=[15401.26,15402.32,15403.45,120.3,122.4] #here are 300 such values b=[1.2,1.4,1.6,1.8,1.7] #here are 300 such values 我想从两个列表中获取每个值,然后计算以下给定的计算: nccn= a*0.4**b print(nccn) 下面是我的代码 enter code here import numpy as np a=15401.54 b=1.2106 nc
a=[15401.26,15402.32,15403.45,120.3,122.4] #here are 300 such values
b=[1.2,1.4,1.6,1.8,1.7] #here are 300 such values
我想从两个列表中获取每个值,然后计算以下给定的计算:
nccn= a*0.4**b
print(nccn)
下面是我的代码
enter code here
import numpy as np
a=15401.54
b=1.2106
nccn= a*0.4**b
print(nccn)
1] 如何为上述问题构造循环。
2] 请建议代码中添加的内容。
3] 各对应值的预期输出在另一行下方的单独行上
感谢您的帮助。使用列表理解
使用numpy
例如:
import numpy as np
a=[15401.26,15402.32,15403.45,120.3,122.4]
b=[1.2,1.4,1.6,1.8,1.7]
# Using list comprehension
print ([i*0.4**j for i,j in zip(a,b)])
# Using numpy
print (np.array(a)*0.4**np.array(b))
输出:
[5128.94736441207, 4270.415472250151, 3555.608938503435, 23.119243105274588, 25.780029089681708]
[5128.94736441 4270.41547225 3555.6089385 23.11924311 25.78002909]
编辑1:
要将结果导出到csv,可以使用pandas(假设附加的依赖项是可以的)
在我看来,你需要这样的东西:
#!/usr/bin/env python3
a=[15401.26,15402.32,15403.45,120.3,122.4]
b=[1.2,1.4,1.6,1.8,1.7]
def MultiplicationArrayElements(a, b):
if (len(a) == len(b)):
print ('Lists are equal in length, let\' sbegin...')
counter = 0
for i in a:
print ('A list is: '+str(a[counter])+' | B list is:'+str(b[counter])+' | nccn is: '+str(a[counter]*0.4*b[counter]))
counter+=1
else:
print ('Lists are NOT equal in length, exit...')
if __name__ == "__main__":
MultiplicationArrayElements(a,b)
非常感谢。它工作得非常顺利。在Python 3.10发布之前,您还需要长度约束,根据PEP 618:“zip()函数现在有一个可选的strict标志,用于要求所有iterables具有相等的长度。”否则,在某些情况下您会陷入困境。我已经得到了输出,但是,我现在想知道如何将其分配给变量,以便将输出导出到excel文件。你能帮个忙吗?@chinu查看更新
[5128.94736441207, 4270.415472250151, 3555.608938503435, 23.119243105274588, 25.780029089681708]
[5128.94736441 4270.41547225 3555.6089385 23.11924311 25.78002909]
import pandas as pd
df = pd.DataFrame( {'a': a, 'b':b})
df['nccn'] = df['a']*0.4**df['b']
df.to_csv('result.csv', index=False)
#!/usr/bin/env python3
a=[15401.26,15402.32,15403.45,120.3,122.4]
b=[1.2,1.4,1.6,1.8,1.7]
def MultiplicationArrayElements(a, b):
if (len(a) == len(b)):
print ('Lists are equal in length, let\' sbegin...')
counter = 0
for i in a:
print ('A list is: '+str(a[counter])+' | B list is:'+str(b[counter])+' | nccn is: '+str(a[counter]*0.4*b[counter]))
counter+=1
else:
print ('Lists are NOT equal in length, exit...')
if __name__ == "__main__":
MultiplicationArrayElements(a,b)