-1

我已经搜索过,但没有找到任何帮助..这是一个例子:

    List.txt
    a
    b
    c
    d

我希望能够得到这样的输出:

    Output.txt
    ab
    ac
    ad
    ba
    bc
    bd
    ca
    cb
    cd
    etc...
4

4 回答 4

2

很直接...

from itertools import permutations

with open('List.txt') as f:    
    letters = (l.strip() for l in f if l.strip())    
    for p in permutations(letters, 2):
        print ''.join(p)

输出:

ab
ac
ad
ba
bc
bd
ca
cb
cd
da
db
dc

一些注意事项:

with语句确保文件在您完成后将被关闭。

letters是一个生成器表达式,在许多情况下(尽管不是这个),它可以让您不必一次读取整个文件。

的用途l.strip()是为了很好地处理输入中出现的意外空行。

itertools.permutations是正确的,NOTitertools.combinations考虑ab==ba并且不会将后者作为输出。

快乐的蟒蛇 :)

于 2011-10-19T19:04:52.053 回答
0
f = open("List.txt")
lines = f.read().splitlines()
lines_new = []
for line in lines:
    for line2 in lines:
        if not line == line2:
            lines_new.append("%s%s" % (line, line2))

print lines_new # ['ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc']
open("Output.txt", "w").write("\n".join(lines_new))

生成一个名为 Output.txt 的文件,其中包含:

ab
ac
ad
ba
bc
bd
ca
cb
cd
da
db
dc
于 2011-10-19T18:42:27.893 回答
0

itertools模块具有组合函数来帮助解决这样的问题:

>>> from itertools import combinations, permutations, product
>>> s = open('list.txt').read().splitlines()
>>> for t in permutations(s, 2):
        print ''.join(t)
于 2011-10-19T18:48:20.337 回答
-1

您可以先将文件读入数组:

lines=[]
for line in file:
  lines.append(line)

然后对其进行迭代以获得所需的输出。

for line1 in lines:
  for line2 in lines:
    print line1+line2

或将其打印到文件中。

于 2011-10-19T18:40:16.680 回答