如何将2个列表中的元素迭代应用到一个新函数中



假设我有两个列表,其中第一个列表的第I个元素对应于第二个列表的第一个元素。如何将两个列表中的元素迭代应用到不同的函数中?

def GetLists(n):
List1 = []
List2 = []
n = int(input("how many terms: "))
for i in range(1,n):
val1 = float(input("what is val1: "))
val2 = float(input("what is the corresponding val2: "))
List1.append(val1)
List2.append(val2)
return List1, List2
def newfunc(ListA, ListB, var):
# take i-th elements from lists A and B where (a,b) are the i-th elements of A and B
# want output = sum(a * var ** b) for index in len(A) if len(A) == len(B)

最像蟒蛇的方式是什么?如果可能的话,我希望不导入外部模块。

编辑:我检查了其他解决方案。"重复"答案需要导入模块;我正试图摆脱它。此外,我正在尝试执行一个返回输出而不是打印值的操作,这使zip的使用变得复杂,超出了重复答案中显示的级别。

从列表A和B中获取第i个元素,其中(A,B)是A和B 的第i个元件

如果len(a)==len(b)

这就是你想要的吗?它将把两个相同长度的列表压缩在一起,为某个常量var计算f(a, b, i) = a[i] * var ** b[i],为每个i计算0 <= i < len(a)。然后返回总和。

def process(list_a, list_b, var):
if len(list_a) != len(list_b):
raise ValueError('Lists are not equal in length')
def combine():
for a, b in zip(list_a, list_b):
yield a * var ** b
return sum(combine())
print(process([5, 2, 3], [2, 2, 3], 10))

输出

3300

该输出是(1 * 10 ** 2) + (2 * 10 ** 2) + (3 * 10 ** 3)的结果。

编辑

上面的方法将组合逻辑(这是你问题的焦点)与求和逻辑解耦。另一种可以说更Python化(根据您的需求)、更短的方法是使用生成器表达式,正如对这个答案的评论中所建议的那样:

def process(list_a, list_b, var):
if len(list_a) != len(list_b):
raise ValueError('Lists are not equal in length')

return sum(a * var ** b for a, b in zip(list_a, list_b))
print(process([1, 2, 3], [2, 2, 3], 10))

从本质上讲,sum中的表达式充当了我在前面的方法中定义的生成器函数combine的匿名替换。

最新更新