找到满足特定条件的对的有效方法
令 A
和 B
为列表。我要找到所有对 {x,y}
,其中 x
位于 A
中,y
位于 < code>B 并且某些条件 Cond[x,y]
为真。这是我想出的,但它相当麻烦,我怀疑有更好的方法
AllPairs[A_, B_, Cond_] := Module[{i, k, C, Cp},
C = {};
For[i = 1, i <= Length[A], i++,
Cp = Select[B, Cond[A[[i]], #] &];
C = C~Join~Table[{A[[i]], Cp[[k]]}, {k, 1, Length[Cp]}];
];
Return[C];
]
例如
In[1]:= AllPairs[{1, 2, 3, 4}, {3, 4, 5}, EvenQ[#1 + #2] &]
Out[1]:= {{1, 3}, {1, 5}, {2, 4}, {3, 3}, {3, 5}, {4, 4}}
我的这段代码的另一个问题是它不容易泛化。我想要一个函数,它接受列表 A1, A2,...,An
和一些条件 Cond[x___]
并输出所有 n 元组 { x1,x2,...,xn}
其中 x1
位于 A1
... xn
位于 中
和 Cond[x1,x2,...,xn]
为 true。
最后,是否有一个内置函数可以计算两个或多个列表的笛卡尔积?
谢谢!
Let A
and B
be lists. I was to find all pairs {x,y}
for which x
is in A
, y
is in B
and some condition Cond[x,y]
is true. This is what I've come up with, but its quite cumbersome and I suspect there is a better way
AllPairs[A_, B_, Cond_] := Module[{i, k, C, Cp},
C = {};
For[i = 1, i <= Length[A], i++,
Cp = Select[B, Cond[A[[i]], #] &];
C = C~Join~Table[{A[[i]], Cp[[k]]}, {k, 1, Length[Cp]}];
];
Return[C];
]
For example
In[1]:= AllPairs[{1, 2, 3, 4}, {3, 4, 5}, EvenQ[#1 + #2] &]
Out[1]:= {{1, 3}, {1, 5}, {2, 4}, {3, 3}, {3, 5}, {4, 4}}
My other problem with this code is that it doesn't generalize easily. I would like to have a function which takes in lists A1, A2,...,An
and some condition Cond[x___]
and outputs all n tuples {x1,x2,...,xn}
for which x1
is in A1
... xn
is in An
and Cond[x1,x2,...,xn]
is true.
And finally, is there a built in function which computes the cartesian product of two or more lists?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您需要检查所有对(即没有对称性可用于减少问题),那么最简单的可能是
Select
和Tuples
:这就是我认为的想要:
关于生成对的更多工具,请查找
Tuples
和Outer
:希望这会有所帮助。
If you need to check all pairs (i.e. there is no symmetry to use for reducing the problem), then the simplest is probably
Select
andTuples
:Which does what I think you want:
As for more tools for generating pairs look up
Tuples
andOuter
:Hope this helps.
对于这样的问题,我个人喜欢使用案例并附加一个条件。不过我不确定效率如何。
我发现这种方法简单且通用,至少对于小型列表(我使用的类型!)
For problems like this I personally like to use Cases and attach a condition. I'm not sure about the efficiency, though.
I find the approach simple and versatile, at least for small lists (of the type I work with!)
另一种解决方案使用
ReplaceList
——它比 Janus 的答案慢大约 4 倍(比原始方法慢 3 倍),但内存效率可能更高。An alternate solution uses
ReplaceList
-- it is about 4 times slower than Janus' answer (and 3 times slower than the original method), but probably more memory efficient.