什么是 zip(函数式编程?)
我最近看到了一些 Clojure 或 Scala(抱歉我对它们不熟悉),它们确实压缩了一个列表或类似的东西。 什么是 zip,它从哪里来?
I recently saw some Clojure or Scala (sorry I'm not familiar with them) and they did zip on a list or something like that. What is zip and where did it come from ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Zip 是指采用两个输入序列并生成一个输出序列,其中使用某个函数将输入序列中同一位置的每两个元素组合在一起。 Haskell 中的一个例子:
输入:
输出:
上面是一个更通用的定义; 有时,
zip
特指将元素组合为元组。 例如,再次在 Haskell 中:输入:
输出:
更通用的版本称为“zip with”。 您可以将“zip”视为“zipWith”的特例:
Zip is when you take two input sequences, and produce an output sequence in which every two elements from input sequences at the same position are combined using some function. An example in Haskell:
Input:
Output:
The above is a more generic definition; sometimes,
zip
specifically refers to combining elements as tuples. E.g. in Haskell again:Input:
Output:
And the more generic version is called "zip with". You may consider "zip" as a special case of "zipWith":
zip 是一种常见的函数式编程方法,如map 或fold。 您会在早期的 lisp 一直到 ruby 和 python 中找到这些函数。 它们旨在对列表执行常见的批处理操作。
在这种特殊情况下,zip 接受两个列表并从这些列表创建一个新的元组列表。
例如,假设您有一个包含 (1,2,3) 的列表,另一个包含 (“一”,“二”,“三”)
如果将它们压缩在一起,您将得到 List((1,"one"), (2,"two"), (3," Three"))
或从 scala 命令行,您将得到:
When I first see在Python中,在不了解函数式编程的情况下,我认为这与压缩格式有关。 在我了解了更多关于函数式编程的知识之后,我越来越多地使用它。
zip is a common functional programming method like map or fold. You will find these functions in early lisps all the way up to ruby and python. They are designed to perform common batch operations on lists.
In this particular case, zip takes two lists and creates a new list of tuples from those lists.
for example, lets say you had a list with (1,2,3) and another with ("one","two","three")
If you zip them together, you will get List((1,"one"), (2,"two"), (3,"three"))
or from the scala command line, you would get:
When I first saw it in Python, without knowing functional programming, I thought it was related to the compression format. After I learned more about functional programming, I've used it more and more.
不幸的是,我没有足够的积分甚至无法对最佳答案发表评论,但
错误,它应该是:
或者简单地说:
Unfortunatley I don't have enough points to even leave a comment on the top answer, but
is wrong, it should be:
or simply:
您可以在 Python 中使用以下代码:
You could use the following code in Python:
帕维尔的回答几乎描述了这一点。 我将仅提供一个 F# 示例:
z
的值将是一个序列,其中包含两个序列中同一位置的项目元组:Pavel's answer pretty much describes it. I'll just provide an F# example:
The value of
z
will be a sequence containing tuples of items in the same position from the two sequences: