在Mathematica中删除大小为零的子列表

lib*_*ias 7 wolfram-mathematica

假设您有一个列表列表,并且您希望仅删除长度为零的列表,例如:

a={{...},{...},{...},...}
DeleteCases[a, ?]
Run Code Online (Sandbox Code Playgroud)

应该?是什么?

Sim*_*mon 11

In[1]:= a={{1,2,3},{4,{5,5.5},{}},{},6,f,f[7],{8}}
Out[1]= {{1,2,3},{4,{5,5.5},{}},{},6,f,f[7],{8}}
Run Code Online (Sandbox Code Playgroud)

这是纳赛尔提供的解决方案:

In[2]:= DeleteCases[a, x_/;Length[x]==0]
Out[2]= {{1,2,3},{4,{5,5.5},{}},f[7],{8}}
Run Code Online (Sandbox Code Playgroud)

请注意,它会删除级别为1的所有长度为零的对象.如果您只想{}从第一级删除长度为零的列表(即),则可以使用

In[3]:= DeleteCases[a, {}]
Out[3]= {{1,2,3},{4,{5,5.5},{}},6,f,f[7],{8}}
Run Code Online (Sandbox Code Playgroud)

或者如果你想从所有级别删除它们然后使用ReplaceAll(/.)

In[4]:= a /. {} -> Sequence[]
Out[4]= {{1,2,3},{4,{5,5.5}},6,f,f[7],{8}}
Run Code Online (Sandbox Code Playgroud)

  • 只要小心`Sequence []`,[它可以吞下你的洞](http://www.imdb.com/title/tt0289605/) (2认同)

Nas*_*ser 5

可能是这样的:

a = {{1, 2, 3}, {4, 5}, {}, {5}}
b = DeleteCases[a, x_ /; Length[x] == 0]


{{1, 2, 3}, {4, 5}, {5}}
Run Code Online (Sandbox Code Playgroud)

  • @Nasser执行`DeleteCases [a,{}]`会更有效率.例如`a = Range/@ RandomInteger [{0,5},10 ^ 6];`那么你的变体在1.2秒内运行,而`DeleteCases [a,{}]`只需要0.15秒. (7认同)