Hypothetical Ninja
Hypothetical Ninja

Reputation: 4077

store loop result in variable,python

i have a list of sentences called "data" and i carried out an operation of soundex.
i dont know how to store it in a variable.. here is my code:

for line in data:

    for word in line.split():

        print jellyfish.soundex(word)   

that gives me a list of soundex codes for all words..

how do i store the results in a variable?? i have tried:

data_new = [(jellyfish.soundex(word) for word in line.split()) for line in data]

but that did not help.

Upvotes: 0

Views: 2636

Answers (3)

BrianO
BrianO

Reputation: 1524

Remove the parentheses around (jellyfish.soundex(word) for word in line.split()), which is a generator expression (see for example generator comprehension). The result,

data_new = [jellyfish.soundex(word) for word in line.split() for line in data]

should give you what you seem to want.

Upvotes: 1

falsetru
falsetru

Reputation: 369074

Use list comprehension instead of generator expression:

data_new = [[jellyfish.soundex(word) for word in line.split()] for line in data] 

Or, if you want flat list:

data_new = [jellyfish.soundex(word) for line in data for word in line.split()]

Upvotes: 1

perreal
perreal

Reputation: 97948

Remove the generator expression from within the comprehension:

data_new = [jellyfish.soundex(word) for line in data for word in line.split() ]

Upvotes: 1

Related Questions