列表理解为修改列表

时间:2017-10-24 04:30:20

标签: python list

我试图通过列表理解修改列表列表中的值。我在创建内部列表时仍然坚持如何实现这一点(请参阅下面的modify_word(j)行)。

#loop through each tweet
for i in all_data: 
    #loop through each word of each tweet
    for j in i: 
        #find the values we're interested in
        if j not in set(all_cities) and meets_criteria(j):
            #here is where I want to make a list of the modified word for each iteration of i (tweet)
            modify_word(j)

我惨遭失败:

 new_data = [[modify_word(j) if (meets_criteria(j) and j not in set(all_cities)) for j in i] for i in all_data]

任何人都知道如何才能做到这一点?一如既往地谢谢。

1 个答案:

答案 0 :(得分:1)

为什么要首先转换?

如果有需要,那么这应该有效

[j for i in all_data for j in i if j not in set(all_cities) and meets_criteria(j)]
  

记住这个的最好方法是for循环内部的顺序   列表理解基于它们出现的顺序   传统的循环方法。最外面的循环首先出现,然后出现   内循环随后。