将循环结果存储在变量python中

时间:2014-02-08 06:18:53

标签: python list

我有一个名为"数据"的句子列表我进行了soundex的操作  我不知道如何将它存储在变量中..这是我的代码:

for line in data:

    for word in line.split():

        print jellyfish.soundex(word)   

给我一​​个所有单词的soundex代码列表..

如何将结果存储在变量中?我试过了:

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

但这没有帮助。

3 个答案:

答案 0 :(得分:1)

从理解中删除生成器表达式:

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

答案 1 :(得分:1)

使用list comprehension而不是generator expression:

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

或者,如果你想要平面列表:

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

答案 2 :(得分:1)

删除(jellyfish.soundex(word) for word in line.split())周围的括号,这是一个生成器表达式(例如参见generator comprehension)。结果,

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

应该给你你想要的东西。