Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表理解以修改列表_Python_List - Fatal编程技术网

Python 列表理解以修改列表

Python 列表理解以修改列表,python,list,Python,List,我试图通过列表理解来修改列表中的值。但是,在创建内部列表时,我一直在讨论如何实现这一点,请参见下面的modify_wordj行 #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) a

我试图通过列表理解来修改列表中的值。但是,在创建内部列表时,我一直在讨论如何实现这一点,请参见下面的modify_wordj行

#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]

有人知道我该怎么做吗?一如既往地感谢。

您首先为什么要转换

如果有需要,那么这应该是可行的

[j for i in all_data for j in i if j not in set(all_cities) and meets_criteria(j)]
记住这一点的最好方法是 列表理解基于它们在列表中出现的顺序 传统的循环方法。最外层的循环首先出现,然后是 随后是内部循环


这真的是个坏主意,因为你的代码会变得不那么可读。是的,这很难看,我同意,但我现在有一个列表,其中有很多垃圾数据,需要根据几个标准进行调整,而不仅仅是简单的替换。有更好的方法吗?用函数包装好吧,让我试试——全新的——感谢您的帮助。