0

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636
Hypothetical Ninja
  • 3,920
  • 13
  • 49
  • 75
  • 1
    Try list comprehension instead of generator expression: `data_new = [[jellyfish.soundex(word) for word in line.split()] for line in data]` – falsetru Feb 08 '14 at 06:21

3 Answers3

1

Remove the generator expression from within the comprehension:

data_new = [jellyfish.soundex(word) for line in data for word in line.split() ]
perreal
  • 94,503
  • 21
  • 155
  • 181
1

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()]
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • could i get back my original list from this?? – Hypothetical Ninja Feb 08 '14 at 06:28
  • @Sword, What do you mean the original list? – falsetru Feb 08 '14 at 06:29
  • yeah.. for an entire intuition abt my problem check http://stackoverflow.com/questions/21628391/replace-words-using-soundex-python – Hypothetical Ninja Feb 08 '14 at 06:30
  • @Sword, If you mean get the `data` from the generated `data_new`. No you can't. (You may use `' '.joni(...)`, but it will not give you exactly same string because `str.split` remove consecutive whitespaces.) – falsetru Feb 08 '14 at 06:34
  • so how do i get alon with it? i was thinking of computing and comparing the soundex in the for loop itself . if it is same , str.replace it with right spelling.. wats ur say? – Hypothetical Ninja Feb 08 '14 at 07:12
  • @Sword, Do you want something like this: `data_new = [''.join(jellyfish.soundex(word) for word in line.split()) for line in data]` ? – falsetru Feb 08 '14 at 07:13
1

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.

Community
  • 1
  • 1
BrianO
  • 1,496
  • 9
  • 12