ActiveState Code

Recipe 65233: Unroll a single-dimension sequence into an HTML unordered list


This function simply takes a single-dimension sequence and converts into into an HTML unordered list. This function makes it simple to present the contents of a sequence on the web in an neat fashion.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def SequenceToUnorderedList(seq):

	html_code = "<ul>" + "\n\n"

	for item in seq:
		html_code = html_code + "<li>" + item + "\n"

	html_code = html_code + "\n" + "</ul>" 

	return html_code

Discussion

Data (whether retrived from a file, database, etc) is usually retrived into a sequence. This function provides a quick way to present this information. I only made this function for one-dimensional sequences, because there would be no uniform way to do multi-dimensional sequences. If I were to make this function for multi-dimensional sequences, it would be unportable and wouldn't scale to every project..

Comments

  1. 1. At 10:08 a.m. on 19 jun 2001, Hamish Lawson said:

    Handle multidimensional lists using recursion. The function could handle multidimensional lists if recursion were used:

    def SequenceToUnorderedList(seq):
        html_code = "&lt;ul>\n"
        for item in seq:
            if type(item) == type([]):
                html_code += SequenceToUnorderedList(item)
            else:
                html_code += "&lt;li>%s&lt;/li>\n" % item
        html_code += "&lt;/ul>\n"
        return html_code
    
  2. 2. At 11:56 a.m. on 11 jul 2001, Tracy Ruggles said:

    Recursion w/ indentation. You could also have it nicely format your recursion:

    def SequenceToUnorderedList(seq,i=1):
        tab = '\t'
        html_code = "%s\n" % (tab*(i-1))
        for item in seq:
            if type(item) == type([]):
                html_code += SequenceToUnorderedList(item, i+1)
            else:
                html_code += "%s%s\n" % (tab*i, item)
        html_code += "%s\n" % (tab*(i-1))
        return html_code
    
  3. 3. At 7:22 p.m. on 21 oct 2001, Scott David Daniels said:

    List Comprehensions are a natural here. A list comprehension may make the body clearer:

    def SequenceToUnorderedList(seq):
        return "\n".join(["&ltul>\n"] +
                   ["&ltli> " + item for item in seq] +
                   ["\n&lt;/ul>\n"])
    

Sign in to comment