简体   繁体   English

如何在没有 for 循环或 lambda 函数的情况下将 function 应用于列表的每个元素?

[英]How to apply a function to each element of a list without for loops or lambda functions?

For example, let's say I have a list:例如,假设我有一个列表:

integer_list = [1, 2, 3, 4]

and I want to plug each element of the list into a formula, like (x*5)+1.我想将列表中的每个元素插入一个公式,例如 (x*5)+1。 How would I do that?我该怎么做? I cannot use for loops or lambda functions.不能使用 for 循环或 lambda 函数。 I can't import any modules either.我也无法导入任何模块。 Right now I am quite literally doing integer_list[0] * 5 + 1 How would I then get the answer from that and multiply every item in the set by it?现在我确实在做integer_list[0] * 5 + 1那么我将如何从中得到答案并将集合中的每个项目乘以它?

Please help!请帮忙!

no lambda no cry没有 lambda 没有哭

def f(x):
    return (x*5)+1

result = list(map(f, integer_list))

Using a for loop should be the right and simplistic solution使用 for 循环应该是正确且简单的解决方案

integer_list = [1, 2, 3, 4]

for (let i = 0; i < integer_list.length; i++){
  console.log((i*5)+1)
}

like so.像这样。

Alternatively, you could use the forEach() method或者,您可以使用 forEach() 方法

integer_list.forEach(num => console.log((num*5)+1))

one line of code.一行代码。 The forEach() method takes in a callback function, then you pass an argument to the function, you can now loop through the array using the argument as the index. forEach() 方法接收一个回调 function,然后将参数传递给 function,您现在可以使用该参数作为索引循环遍历数组。 Hope this was helpful.希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM