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

时间:2015-09-15 14:12:49

标签: python list-comprehension

我正在练习列表理解,但无法正确理解。

例如,我怎样才能逐步完成下面的代码(它完美地工作,我把它写成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,

2 个答案:

答案 0 :(得分:1)

以下内容将在元组列表中生成最里面的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))

如果你需要一个压缩字的 flat 列表,那么你需要第三个循环:

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]

答案 1 :(得分:0)

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

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