将 `GatherBy` 的转换应用到不同的列表 [英] Applying transformation of `GatherBy` to a different list

查看:23
本文介绍了将 `GatherBy` 的转换应用到不同的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有相同大小的 listAlistB.我正在对 listA 执行 GatherBy,它重新排列该列表.将相同的重排应用到 listB 的优雅方式是什么?

I have listA and listB of the same size. I'm doing GatherBy on listA, which rearranges that list. What is an elegant way to apply identical rearrangement to listB?

例如

listA = {1, 2, 3};
listB = {a, b, c};
listA1 = GatherBy[{1, 2, 3}, OddQ];

listB1 应该变成 {{a, c}, {b}}

更新感谢有趣的想法,我最终做了一些类似于 belisarius 的事情.这让我想起了 Python 的装饰-排序-取消装饰"模式

Update Thanks for interesting ideas, I eventually ended up doing something similar to belisarius. This reminds me of Python's "decorate-sort-undecorate" pattern

decorated = Thread[{listA, listB}];
grouped = GatherBy[decorated, OddQ[First[#]] &];
listB1 = Map[Last, grouped, {2}]

推荐答案

好吧,第一次第二次尝试:

(警告警告......优雅"是一个完全主观的概念)

(Warning Warning ... "elegance" is an utterly subjective concept)

gBoth[lslave_, lmaster_, f_] := 
                 {Part[#, All, All, 1], Part[#, All, All, 2]} &@ 
                 GatherBy[Transpose[{lslave, lmaster}], f[#[[2]]] &]

lmaster = {1, 2, 3};
lslave = {a, b, c};  

{lslave1, lmaster1} = gBoth[lslave, lmaster, OddQ]  

出来

{{{a, c}, {b}}, {{1, 3}, {2}}}  

编辑

请注意,要运行此代码,您必须具有

Note that for this code to run you must have

 Dimensions[lslave][[1;;Length[Dimensions@lmaster]]] == Dimensions@lmaster  

但是两个列表更深层次的内部结构可能不同.例如:

but the deeper internal structure of both lists could be different. For example:

lmaster = {{1, 2, 3}, {2, 3, 4}};
lslave = {{{a}, {b}, {c}}, {{a}, {b}, {c}}};

{lslave1, lmaster1} = gBoth[lslave, lmaster, #[[1]] < 3 &]

出来

{{{{{a}, {b}, {c}}, {{a}, {b}, {c}}}}, {{{1, 2, 3}, {2, 3, 4}}}}

HTH!

这篇关于将 `GatherBy` 的转换应用到不同的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆