对 Mathematica 列表中每个元素的第二个组件进行运算
我可以使用以下方法对列表中每个元素的第一个组件进行一些操作(在本例中为 ToString
):
{ToString@#[[1]], Rest@#}~Flatten~1 & /@ {{1, 2}, {3, 4, 5}}
但是,我有几个问题:
- 它不适用于
{ToString@#[[1]], Rest@#}~压平~1 & /@{{1, 2}, 2, {3, 4, 5}}
原因显而易见。如何让它也能工作 这个案子?预期输出为{{"1", 2}, 2, {"3", 4, 5}}
。 - 如何轻松对第二个(或第三个等)组件执行此操作?即我希望输出为
{{0}, {1, "2"}, {3, "4", 5}, {6, "7", 9, 10}}
- 是有一种方法可以使用模式/规则(比如
/.{#[[1]]->ToString[#[[1]]]}
) 对于这种操作?所以请列出您可能想到的所有解决方案,无论效率如何。
多谢!
I can use the following way to do some operation (in this case ToString
) for the first component of each element in a list:
{ToString@#[[1]], Rest@#}~Flatten~1 & /@ {{1, 2}, {3, 4, 5}}
However, I have a few questions:
- It does not work for
{ToString@#[[1]], Rest@#}~Flatten~1 & /@ {{1,
for obvious reason. How to make it also work in
2}, 2, {3, 4, 5}}
this case? The expected output would be{{"1", 2}, 2, {"3", 4, 5}}
. - How to do this for the second(or third, etc.) component easily? I.e. I want the output to be
{{0}, {1, "2"}, {3, "4", 5}, {6, "7", 9, 10}}
- Is there a way to use pattern/rule (like
/.{#[[1]]->ToString[#[[1]]]}
) for this kind of operation? So please list all solutions you may think of regardless of the efficiency.
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
直到我编写了它之后,我才意识到这与 Leonid 的核心功能相同。也许这仍然表明这可能比他相当复杂的职能更透明一些。
然后可以使用
{x:Repeated[_, {4}], a_, b__} :> {x, ToString@a, b}, 1]
用于第五个索引,依此类推。I didn't realize this was the same as Leonid's core function until I had written it. Still perhaps that says that this may be a little more transparent than his rather elaborate function.
One can then use
{x:Repeated[_, {4}], a_, b__} :> {x, ToString@a, b}, 1]
for the fifth index, etc.下面的函数基本上应该做你想做的事:
并且可以接受规则。例如:
The following function should basically do what you want:
and can accept rules. For example:
另一种方便的方法可能是将
ReplacePart
与RuleDelayed
一起使用,例如,将每个子列表的第 3 部分(如果存在)转换为字符串:
给出输出:
类似地,要将每个子列表的第 1 部分转换为字符串:
给出:
Another convenient method might be to use
ReplacePart
together withRuleDelayed
For example, to turn part 3 of each sublist (if it exists) into a string:
gives as output:
Similarly, to turn part 1 of each sublist into a string:
giving:
从长远来看,我认为这可能是一种更简单的方法,即使它并不完全符合您的要求:
您可以根据需要向
rep
的定义添加任意模式和条件。In the long run I think that this might be an easier approach, even if it is not exactly what you requested:
You can add arbitrary patterns and conditions to the definition of
rep
as needed.