3

I have the following two lists

l1 = {{{2011, 3, 13}, 1}, {{2011, 3, 14}, 1}, {{2011, 3, 15}, 
    1}, {{2011, 3, 16}, 2}, {{2011, 3, 17}, 3}};
l2 = {{{2011, 3, 13}, 40}, {{2011, 3, 16}, 50}, {{2011, 3, 17}, 60}};

and I need to extract items from l2 whose date (the first element of each l2 element) matches dates in l1 (so as to produce two lists of exactly the same length)

I don't see why something like:

Select[l1, MemberQ[Transpose[l2][[1]], #[[1]]]]

should produce an empty list. Am I missing something trivial?

4

5 に答える 5

7

アンパサンドを忘れました。そのはず

Select[l1, MemberQ[Transpose[l2][[1]], #[[1]]]&]
于 2011-04-20T22:17:43.993 に答える
4

Sjoerd は、メソッドを機能させる方法を示していますが、最適ではありません。問題は、Transpose[l2][[1]]のすべての要素に対して が再度評価されることですl1。David は、そのステップを 1 回だけ実行するメソッドを提供します。以下を使用することもできます。

Cases[l1, {Alternatives @@ l2[[All, 1]], _}]
于 2011-04-20T22:50:17.897 に答える
3

リストが大きくなったときのより高速な方法:

DeleteCases[GatherBy[Join[l1, l2], First], {_}][[All, 1]]

(*  Out= {{{2011, 3, 13}, 40}, {{2011, 3, 16}, 50}, {{2011, 3, 17}, 60}}  *)

リストに重複が含まれている可能性がある場合は、

l1 = GatherBy[l1, First][[All, 1]]

最初に重複を削除します。

于 2011-04-21T04:07:43.300 に答える
2

これはもしかして、あなたが考えていることですか?

dates=Transpose[l2][[1]];
Cases[l1, {x_, _} /; MemberQ[dates, x]]
于 2011-04-20T22:10:28.340 に答える
1

これが私の非ソート交差コードです:

NonSortingIntersection[l1_, l2_, test_: SameQ] := 
 Module[{res = 
    Last@Reap[
      Scan[Extract[l1, 
         Position[l1, x_ /; test[x, #], {1}, 1, Heads -> False], 
         Sow] &, l2]]}, If[res === {}, res, First[res]]]

使用法は次のとおりです。

In[22]:= NonSortingIntersection[l1, l2, 
 Function[{x, y}, First[x] == First[y]]]

Out[22]= {{{2011, 3, 13}, 1}, {{2011, 3, 16}, 2}, {{2011, 3, 17}, 3}}

他のソリューションとは異なり、出力の長さは よりも長くないことが保証されていることに注意してくださいl2。例えば:

In[24]:= Cases[Join[l1, l1], {x_, _} /; MemberQ[Evaluate[Transpose[l2][[1]]], x]]

Out[24]= {{{2011, 3, 13}, 1}, {{2011, 3, 16}, 2}, {{2011, 3, 17}, 
  3}, {{2011, 3, 13}, 1}, {{2011, 3, 16}, 2}, {{2011, 3, 17}, 3}}

In[25]:= NonSortingIntersection[Join[l1, l1], l2, 
 Function[{x, y}, First[x] == First[y]]]

Out[25]= {{{2011, 3, 13}, 1}, {{2011, 3, 16}, 2}, {{2011, 3, 17}, 3}}

これは望ましい場合とそうでない場合がありますが、問題をよく知っている radhat 次第です。

于 2011-04-21T01:03:12.357 に答える