How to get clean code for a gallery?

You can try to overwrite the gallery shortcode with:

add_shortcode( 'gallery', 'custom_gallery_shortcode' );

where the shortcode callback is:

/**
 * Overwrite the native  shortcode, to modify the HTML layout.
 */
function custom_gallery_shortcode( $attr = array(), $content="" )
{
        $attr['itemtag']        = "li";
        $attr['icontag']        = "";
        $attr['captiontag']     = "p";

        // Run the native gallery shortcode callback:    
        $html = gallery_shortcode( $attr );

        // Remove all tags except a, img,li, p
        $html = strip_tags( $html, '<a><img><li><p>' );

        // Some trivial replacements:
        $from = array(  
            "class="gallery-item"", 
            "class="gallery-icon landscape"", 
            'class="attachment-thumbnail"',
            'a href="https://wordpress.stackexchange.com/questions/140681/, 
        );              
        $to = array("',
            '',
            'class="tnggallery"', 
            'a class="lightbox" href=", 
        );
        $html = str_replace( $from, $to, $html );

        // Remove width/height attributes:
        $html = preg_replace( "/(width|height)=\"\d*\"\s/', "", $html );

        // Wrap the output in ul tags:
        $html = sprintf( '<ul class="gallery">%s</ul>', $html );

        return $html;
}

to modify the HTML layout.