Extract strings from nested lists in Python

Possible duplicate:
Smooth (irregular) list of lists in Python

I am trying to use the nltk library in python and, more specifically, wordnet corpus to extract all words in a broad semantic category, such as "animal". I managed to write a function that goes through all the categories and extracts the words in them, but in the end I get a huge number of lists in the lists. Lists do not have a predicted length or depth; they look like this:

['pet', 'pest', 'mate', 'young', 'stunt', 'giant', ['hen', 'dam', 'filly'], ['head', 'stray', 'dog', ['puppy', 'toy', 'spitz', 'pooch', 'doggy', 'cur', 'mutt', 'pug', 'corgi', ['Peke'], ['chow'], ['feist', 'fice'], ['hound', ['Lhasa', 'cairn']], ['boxer', 'husky']], ['tabby', 'tabby', 'queen', 'Manx', 'tom', 'kitty', 'puss', 'pussy', ['gib']]]

What I want is to be able to grab each of these lines from it and return one unaccounted list. Any tips?

+1
source share
1 answer

, , . , HTML ( ), ( ) ..

, , , :

ll = [ 1, 2, 3, [4, 5, [6, 7, 8]]]

def flatten(input_list):
    output_list = []
    for element in input_list:
        if type(element) == list:
            output_list.extend(flatten(element))
        else:
            output_list.append(element)
    return output_list

print (flatten(ll)) #prints [1, 2, 3, 4, 5, 6, 7, 8]

, , , ( ), , - , - , .

, , , ( .)

  • . compsci. - , .
+3

All Articles