如何在Python中合并单个文本文件的行?
我已经搜索过,但没有找到任何帮助。这是一个例子:
List.txt
a
b
c
d
我希望能够得到这样的输出:
Output.txt
ab
ac
ad
ba
bc
bd
ca
cb
cd
etc...
I've searched, but found nothing to help.. This is an example:
List.txt
a
b
c
d
I want to be able to get an output like this:
Output.txt
ab
ac
ad
ba
bc
bd
ca
cb
cd
etc...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
itertools 模块具有组合函数来帮助解决此类问题:
The itertools module has combinatoric functions to help with problems like this one:
您可以首先将文件读入数组:
然后迭代它以获得所需的输出。
或将其打印到文件中。
You can first read the file into an array:
and then iterate over it to get the desired output.
or print it to a file instead.
非常简单...
输出:
一些注释:
with
语句确保文件在使用完毕后将被关闭。letters
是一个生成器表达式,在许多情况下(尽管不是这个)它可以让您不必一次读取整个文件。使用
l.strip()
旨在很好地处理输入中出现的意外空行。itertools.permutations
是正确的,而不是itertools.combinations
,它认为ab
==ba
并且不包括后者作为输出。快乐的蟒蛇:)
Pretty straightforward...
Output:
Some notes:
The
with
statement ensures the file will be closed when you're done with it.letters
is a generator expression, which in many cases (though not this one) will save you from having to read the entire file in at once.The uses of
l.strip()
are meant to nicely handle accidental blank lines if present in input.itertools.permutations
is correct, NOTitertools.combinations
which considersab
==ba
and will not include the latter as output.Happy pythoning :)
生成一个名为 Output.txt 的文件,其中包含:
Results in a file called Output.txt with: