假设我有一个嵌套列表:{{2,0,3},{4,0,4},{0,0,9}}
。我想将所有0
更改为0.00001
或其他一些小值,以便最终结果为{{2,0.00001,3},{4,0.00001,4},{0.00001,0.00001,9}}
如果不使用For
和If
函数,我该怎么做呢?
提前致谢。
答案 0 :(得分:4)
也许更好的解决方案是允许除以零,但禁止警告:
In[1]:= Quiet[1/{{2, 0, 3}, {4, 0, 4}, {0, 0, 9}}, Power::infy]
Out[1]= {{1/2,ComplexInfinity,1/3}, {1/4,ComplexInfinity,1/4}, {ComplexInfinity,ComplexInfinity,1/9}}
但我想如果你想用0.00001替换Integer
0,那么你可以试试
In[2]:= {{2, 0, 3}, {4, 0, 4}, {0, 0, 9}} /. 0 -> 0.00001
1/%
Out[2]= {{2,0.00001,3},{4,0.00001,4},{0.00001,0.00001,9}}
Out[3]= {{1/2,100000.,1/3},{1/4,100000.,1/4},{100000.,100000.,1/9}}
答案 1 :(得分:3)
{{2, 0, 3}, {4, 0, 4}, {0, 0, 9}} /. {0 -> 0.0001}
(*
-> {{2,0.0001,3},{4,0.0001,4},{0.0001,0.0001,9}}
*)
然而,正如@nomulous所说,这不可能是实现你所追求的一切的最好方式。那么,你想做什么?你想解决的实际问题是什么?
编辑:在你的评论中,你提到你正试图分割图像。没有看到更多的代码,我建议这样的事情:
i1 = Image[ {{0, 1, 0}, {1, 0, 1}, {0, 1, 0}}]
i2 = Image[ RandomReal[1, {3, 3}]]
Image[Quiet[i2[[1]]/i1[[1]]] /. ComplexInfinity -> 1]
提取数据列表,划分,允许除以零,产生ComplexInfinity
,将ComplexInfinity
替换为1(允许的最大值),然后在结果列表周围包裹Image
也许如果你展示更多代码,就会更容易提出更好的建议。