How can I make a list of what objects are connected to what shading groups?

Here’s an example of how to make a list of what objects are connected to what shading group:

for ($SG in $listofShadinggroups) {
 string $connectedObjects[] = `sets -q $SG`;
 for ($connectedObject in $connectedObjects){
 print ( $connectedObject + " is connected to " + $SG + "\n");
 }
 }