If you want people to be able to help you well, you’ve got to give self-contained examples of whatever’s the problem. This means including an entire function, along with the data necessary to run it. See Please read: make it easier to help you
But don’t give us the huge function as in your actual code, rather you should produce a self-contained example that’s representative of your issue.
Pretty sure they meant to deduplicate your code by assigning the common expressions to variables:
h1 = XYZlayers[1][xy]
h2 = XYZlayers[2][xy]
h3 = XYZlayers[3][xy]
If nothing else, that would make the code read better.