我已经搜索过,但没有找到任何帮助..这是一个例子:
List.txt
a
b
c
d
我希望能够得到这样的输出:
Output.txt
ab
ac
ad
ba
bc
bd
ca
cb
cd
etc...
我已经搜索过,但没有找到任何帮助..这是一个例子:
List.txt
a
b
c
d
我希望能够得到这样的输出:
Output.txt
ab
ac
ad
ba
bc
bd
ca
cb
cd
etc...
很直接...
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
并且不会将后者作为输出。
快乐的蟒蛇 :)
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
itertools模块具有组合函数来帮助解决这样的问题:
>>> from itertools import combinations, permutations, product
>>> s = open('list.txt').read().splitlines()
>>> for t in permutations(s, 2):
print ''.join(t)
您可以先将文件读入数组:
lines=[]
for line in file:
lines.append(line)
然后对其进行迭代以获得所需的输出。
for line1 in lines:
for line2 in lines:
print line1+line2
或将其打印到文件中。