in a nested list how to test whether a given indexing sequence is valid in mathematica
I have a highly irregular nested list myList
in mma, whenever I am given a integer sequence, such as 1,1,2,3,1
of any length, I want to kn开发者_如何学编程ow if
myList[[1,1,2,3,1]]
is valid; because if it is not, then I will get an error saying
Part::partw: part... does not exist
Thanks.
Quiet[
Check[mylist[[1, 1, 2, 3, 1]], Print[False], Part::partd],
Part::partd];
You can replace Print[False] for any other action ...
Edit
To check for both partd and partw messages the syntax is:
Quiet[Check[{{{1, 3}}, {2}}[[1, 4, 2, 3, 1]],
Print[False], {Part::partd, Part::partw}],
{Part::partd, Part::partw}];
HTH!
Coincidently this came up on MathGroup a few weeks ago. Below is a URL to what I believe was the last and best response (from Ray Koopman).
http://forums.wolfram.com/mathgroup/archive/2011/Jan/msg00326.html
It also has links to earlier posts in the same thread.
Daniel Lichtblau
Wolfram Research
Here is another way of doing it.
Quiet[MemberQ[#, #[[1, 4, 2, 3, 1]], Infinity] &[{{{1, 3}}, {2}}]]
Returns False.
It will essentially return true or false after checking to see whether the element at that position (if it exists) is in the list.
Quiet[MemberQ[#, #[[1, 1, 2]], Infinity] &[{{{1, 3}}, {2}}]]
Returns True.
belisarius's answer will give more low level control though.
精彩评论