Sanitize an abused list

It is often necessary to sanitize lists after substantial use and whilst using mixed sources. This is one of many ways you can achieve this with minimal effort. Apologies for the line return in the WP template. Update: no more apologies for the line return as this should be fixed. I recently update the template with a new style. Hope you like the template and the abused list function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    def flattenlist(L):
        import types
        WhiteTypes = ('StringType', 'UnicodeType', 'StringTypes', 'ListType', 'ObjectType', 'TupleType')
        BlackTypes= tuple( [getattr(types, x) for x in dir(types) if not x.startswith('_') and x not in whites] )
 
        tmp = []
        def core(L):
            if  not hasattr(L,'__iter__'):
                return [L]
            else :
                for i in L:
                    if isinstance(i,BlackTypes):
                        tmp.append(i)
                        continue
                    if type(i) == type(str()):
                        tmp.append(i)
                    else:
                        core(i)
            return tmp
        return core(L)


3 Comments

  1. Marcus B. wrote:

    Very helpful! I have searched for something to cure my nasty list woes for a while and finally google has delivered me you! I think this will help me from bashing our Oracle DBA over the head with a hammer for allowing so many shit string types in the db :)

  2. direnzo wrote:

    Thanks for this! Never thought to incorporate type checking.

  3. Cody wrote:

    hahahahahahaha. too simple!