简体   繁体   English

嵌套for循环遍历文本文件中的每个组合

[英]Nested for loop to go through every combination in text file

Below is the code I have: 以下是我的代码:

with open('test.txt') as f:
    for i in f:

        for j in f:

            pw_n= i+j
            print(pw_n)

Sample data from test.txt is: test.txt中的示例数据是:

USA
Canada
Mexico
China
Russia

Output Currently: 目前输出:

USA
CANADA

USA
MEXICO

USA
China

USA
Russia

The above is great but I would like it to go through all iterations. 以上是很好的,但我希望它经历所有迭代。 So, after it finishes USA, I would like it to go to Canada then Mexico, etc... Ex.: 所以,在完成美国之后,我希望它能够去加拿大,然后是墨西哥等等。

Canada
USA

Canada
Canada

Canada
Mexico
..........

Any help regarding this would be great. 对此有任何帮助都会很棒。 I've tried to increment 'i' by 1 but that wasn't working. 我试图将'i'增加1但这不起作用。

Thanks! 谢谢!

Take a look at https://docs.python.org/3.4/library/itertools.html#itertools.permutations 看看https://docs.python.org/3.4/library/itertools.html#itertools.permutations

>>> list(permutations(['USA', 'Canada', 'Mexico'], 2)) 
[
    ('USA', 'Canada'), 
    ('USA', 'Mexico'), 
    ('Canada', 'USA'), 
    ('Canada', 'Mexico'), 
    ('Mexico', 'USA'), 
    ('Mexico', 'Canada')
]

Here is one solution 这是一个解决方案

with open('test.txt') as f:
    lines = f.readlines()

for i, val in enumerate(lines):
    for j in range(i+1, len(lines)):
        print("%s%s" %(val, lines[j]))
    print("")

If you want to stay as close as possible to your current code, you should use file.readlines() : 如果您希望尽可能接近当前代码,则应使用file.readlines()

with open('test.txt') as f:
    lines = f.readlines()
    for i in lines:
        for j in lines:
            pw_n = i + j
            print(pw_n)

As an addition, I would recommend changing lines = f.readlines() to: 另外,我建议将lines = f.readlines()更改为:

lines = [x.rstrip('\n') + '\n' for x in f.readlines()]

That list comprehension will force all words to end with a '\\n' (in your file Russia doesn't have any '\\n' at the end and so it is shown differently on the output, this fixes that). 该列表理解将迫使所有单词以'\\n'结尾(在您的文件中Russia没有'\\n' ,因此在输出中显示不同,这解决了这个问题)。

If you are looking for a better code you should use itertools.permutations(iterable, r=None) , where r is the number of items per combinations (in this case we need 2) 如果您正在寻找更好的代码,您应该使用itertools.permutations(iterable, r=None) ,其中r是每个组合的项目数(在这种情况下,我们需要2)

from itertools import permutations
with open('test.txt') as f:
    for x, y in permutations(f.readlines(), 2):
        print(x + y)

You may also improve this code by adding: 您还可以通过添加以下内容来改进此代码

for x, y in permutations((x.rstrip('\n') + '\n' for x in f.readlines()), 2):

Here a list comprehension isn't needed, instead, we can use a generator expression, which is more memory friendly. 这里不需要列表理解,相反,我们可以使用生成器表达式,它更加内存友好。

Since you are iterating over each permutation inside a for loop, in no moment you need to store it as a list, that means you don't need to store on memory all the permutations at the same time, instead, they are calculated as you use them. 因为你在for循环中迭代每个排列,所以你不需要将它存储为列表,这意味着你不需要同时在内存中存储所有排列,相反,它们会像你一样计算使用它们。 The same applies to the generator expression, you don't store it in opposition with the list comprehension from the first code. 这同样适用于生成器表达式,您不会将其与第一个代码中的列表解析相对应地存储。

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

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