如何将列表 {element,...} 转换为元组列表 {{i,element},...}?
给定一些列表,
numbers = {2,3,5,7,11,13};
我该如何
translatedNumbers = {{1,2},{2,3},{3,5},{4,7},{5,11},{6,13}}
简洁地翻译它?
我知道如何使用程序编程风格来执行此操作,如下所示:
Module[{lst = {}, numbers = {2, 3, 5, 7, 11, 13}},
Do[AppendTo[lst, {i, numbers[[i]]}], {i, 1, Length@numbers}]; lst]
但是对于在我看来简单的操作来说,这是相当冗长的。例如,与此等效的 haskell 是
numbers = zip [1..] [2,3,5,7,11,13]
我忍不住认为有一种更简洁的方法可以在 Mathematica 中“索引”数字列表。
潜在的答案
显然,除非我有 100 个“代表”,否则在灯泡熄灭后我不被允许回答我自己的问题。所以我就把我的答案放在这里。让我知道我是否应该做一些与我所做的不同的事情。
问完这个问题后我现在感觉有点傻。因为如果我将 mathematica 列表视为矩阵,我就可以转置它们。因此,我的问题的答案(也许不是最好的)如下:
Transpose[{Range@6, {2, 3, 5, 7, 11, 13}}]
编辑为任意输入列表工作,我认为类似:
With[{lst={2, 3, 5, 7, 11, 13}},Transpose[{Range@Length@lst,lst}]]
会起作用。我还能做得更好吗?
Given some list
numbers = {2,3,5,7,11,13};
How do I translate this to
translatedNumbers = {{1,2},{2,3},{3,5},{4,7},{5,11},{6,13}}
concisely?
I am aware of how to do this using the procedural style of programming as follows:
Module[{lst = {}, numbers = {2, 3, 5, 7, 11, 13}},
Do[AppendTo[lst, {i, numbers[[i]]}], {i, 1, Length@numbers}]; lst]
But such is fairly verbose for what seems to me to be a simple operation. For example the haskell equivalent of this is
numbers = zip [1..] [2,3,5,7,11,13]
I can't help but think that there is a more concise way of "indexing" a list of numbers in Mathematica.
Potential Answer
Apparently I'm not allowed to answer my own question after having had a lightbulb go off unless I have 100 "rep". So I'll just put my answer here. Let me know if I should do anything differently then I have done.
Well I'm feeling a little silly now after having asked this. For if I treat mathematica lists as a matrix I'm able to transpose them. Thus an answer (perhaps not the best) to my question is as follows:
Transpose[{Range@6, {2, 3, 5, 7, 11, 13}}]
Edited to work for arbitrary input lists, I think something like:
With[{lst={2, 3, 5, 7, 11, 13}},Transpose[{Range@Length@lst,lst}]]
will work. Could I do any better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
需要考虑的一件事是转换是否不会解压数据。这对于大型数据集很重要。
这将解压
这不会
One thing to consider is if the transformation will not unpack the data. This is important for large data sets.
This will unpack
this will not
我会使用 MapIndexed 代替
I would use MapIndexed instead
好吧,我的“解决方案”可能不如 cobbal 的解决方案那么聪明,但是当我用长数组测试它时,它更快(5 倍!)。
我只是用:
啊! ruebenko 在我写帖子期间发布了类似的答案。很抱歉这个几乎是多余的帖子。好吧,也许这并不是那么多余。我已经测试了带包装和不带包装的解决方案,并且在不包装的情况下它的工作速度最快。
Well, my „solution“ is perhaps not as smart as the solution from cobbal, but when I test it with long arrays, it is faster (factor of 5!).
I am simply using:
AHH! ruebenko posted a similar answer during I have written my post. Sorry for this almost superfluous post. Well, perhaps it is not so superfluous. I have tested my solution with and without packing, and it works at fastest without packing.