简体   繁体   English

列表理解以修改列表

[英]List comprehension to Modify a List

I'm trying to modify values in a list of list via list comprehension. 我正在尝试通过列表理解来修改列表列表中的值。 I'm stuck on how to implement this though when creating the inner list (please see modify_word(j) line below). 尽管在创建内部列表时,我仍然停留在如何实现这一点上(请参见下面的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)

I failed miserably with this: 我为此惨败:

 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]

Anyone have an idea on how I might be able to do this? 有人对我如何能够做到这一点有想法吗? Thanks as always. 一如既往的感谢。

Why do you want to convert in the first place? 为什么首先要转换?

If there is a need then this should work 如果有需要,那应该可以

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

The best way to remember this is that the order of for loop inside the list comprehension is based on the order in which they appear in traditional loop approach. 记住这一点的最好方法是,列表理解中for循环的顺序基于它们在传统循环方法中出现的顺序。 Outer most loop comes first, and then the inner loops subsequently. 最外面的循环先到,然后是内部循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM