用地图替换循环
我正在尝试在我的代码中删除for循环,并尝试使用地图和功能。对于循环,我的代码正常工作,但我不知道如何使用地图以及在哪里功能获得相同的输出。我尝试了,但是在地图中创建类实例时,我会遇到错误。我不知道在地图中写什么以及在哪里起作用。
I am trying to remove the for loop in my code and trying to use the map and where function. With for loop my code is working fine but I don't know how to use the map and where function to get the same output. I tried but I am getting errors while creating an instance of class inside the map. I don't know what to write inside the map and where functions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基于循环和(如果),您可以直接使用列表来添加到列表:
listeral也可以使用
MAP
,编写。展开
和其中
在几种方法,但没有一个直接。
棘手的一点是您正在做两个循环,然后是IF。
一种方法是:
这使用
展开
,因为内部地图
可以创建多个(或零)结果。那不是地图
擅长的东西。另一种方法可能是首先创建所有对,然后对它们进行过滤:
更紧密地遵循Listeral的逻辑,在两个文章列表上进行循环,然后对成对进行过滤。
它不那么可读,需要一个辅助类型来表示对。
总而言之,列表的文字符号更可读,并且使用
map
,展开
,wenty < /code>和
tolist
。 (有时候,它只需要您将更复杂的计算移动到辅助功能中,这可以说也可以提高可读性。)简而言之,有时您需要
Expand
以及map
在转换列表中将列表创建到峰值方法调用时。Adding to a list, based on a loop and an
if
, is something you can do directly with a list literal:That listeral can also be written using
map
,expand
andwhere
in afew ways, but none will be as direct.
The tricky bit is that you are doing two loops, then the if.
One approach would be:
This uses
expand
because the innermap
can create multiple (or zero) results. That's not somethingmap
is good at.Another approach could be creating all the pairs first, then filtering them:
That more closely follows the logic of the listeral, doing loops over the two article lists, then filtering on the pairs.
It's not as readable, and requires a helper type to represent the pair.
All in all, the list literal notation is more readable and as powerful as anything you can do with
map
,expand
,where
andtoList
. (Sometimes it just requires you to move more complicated computations into helper functions, which can, arguably, improve readability too.)In short, sometimes you need
expand
as well asmap
andwhere
when converting loops that create lists into iterable method calls.请检查以下两种不同的方法。
第一个
第二
第三
第四
您可以通过
如果您有其他疑问,请随时写在评论中。
Please check the following two different approaches.
First
Second
Third
Fourth
You can access the complete source code through GitHub.
If you have further questions, please don't hesitate to write in the comments.