Selecting with Cases

三世轮回 提交于 2019-12-23 17:50:25

问题


Please Consider :

Subsets[Flatten[ParallelTable[{i, j}, {i, 1, 96}, {j, 1, 4}], 1], {4}]

I need to select all the Sublist such that the the i value is never the same within each sublist of 4

{{3,1},{4,1},{5,1},{6,1}} should be accepted while {{1,1},{1,2},{2,3},{6,1}} should be rejected. The Value 1 for i being repeated 2 times.

I know I could do this with Cases, but don`t understand the Syntax of it, and find the help on Cases rather empty compared to its potential applications.


回答1:


Assuming your data is in the variable data, the following should do it:

Select[data, Length@Union[#[[All, 1]]] === 4 &]

This takes the "i"-value (i.e. first element), and checks that the 4 values are all different (i.e. if we remove the duplicates we still have 4 of them)




回答2:


This response assumes that the input data is a list of tuples of four pairs each, e.g.:

$data = {{{3, 1}, {4, 1}, {5, 1}, {6, 1}} , {{1, 1}, {1, 2}, {2, 3}, {6, 1}}};

Using Cases, one could name and compare the first elements of each pair to ensure that they are unequal:

Cases[
  $data
, {{a_, _}, {b_, _}, {c_, _}, {d_, _}} /; Unequal[a, b, c, d]
]

Another use of Cases compares the first elements of each pair without naming them:

Cases[
  $data
, tuple_ /; Unequal @@ tuple[[All, 1]]
]

Alternatively, one could use DeleteCases and exclude tuples with at least two pairs with the same initial value:

DeleteCases[
  $data
, {___, {a_, _}, ___, {a_, _}, ___}
]

One might think that this last expression could be:

(* warning: does not work *)
Cases[$data, Except[{___, {a_, _}, ___, {a_, _}, ___}]]

... but Except does not permit named patterns in the first argument.




回答3:


WReach already covered Cases well, so here is another approach.

Pick[data, Signature /@ data[[All, All, 1]], 1 | -1]

It is faster than most of the other methods, but still not as fast as the fixed-length Cases method.



来源:https://stackoverflow.com/questions/7892994/selecting-with-cases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!