如何处理列表理解解决方案?

How to approach for a list comprehension solution?

我正在练习列表理解,但无法正确获得直觉。

例如,对于下面这段代码(它工作得很好,我已经把它写成This question的解决方案),我应该如何一步步进行,并将这个解决方案转化为列表推导式解决方案?有简短解释的答案会很好。

with open("example.txt","r") as first, open("output.txt","r") as second:

    for i,j in zip(first,second):
        first_list = i.split()
        second_list = j.split()
        for i,j in  zip(first_list, second_list):
            print i,j,

以下将生成元组列表中最内层的 i, j 值:

with open("example.txt","r") as first, open("output.txt","r") as second:
    result = [(word1, word2) for line1, line2 in zip(first, second) for word1, word2 in zip(line1.split(), line2.split())]

我已将您的变量名替换为不那么晦涩的变量名。

以上可以写成嵌套循环:

 for line1, line2 in zip(first, second):
     for word1, word2 in zip(line1.split(), line2.split():
         outputlist.append((word1, word2))

如果你需要一个平坦的压缩单词列表,那么你需要第三个循环:

with open("example.txt","r") as first, open("output.txt","r") as second:
    result = [word 
              for line1, line2 in zip(first, second)
              for combo in zip(line1.split(), line2.split())
              for word in combo]

通过列表理解,您可以获得预期值的列表:

with open("example.txt","r") as first, open("output.txt","r") as second:
    my_list=[(t,k) for i,j in zip(first,second) for t,k in zip(i.split(),j.split())]

然后,如果你想打印项目,你可以遍历 my_list 并打印它们。

for i,j in my_list:
    print i,j