首页 > 解决方案 > 将两行打印为单行,但每个源行中都有备用字符

问题描述

我有 file.txt 包含两行:

this is one
and my pen

输出应该像在单行中打印每一行的每一列:

tahnids imsy opneen

我们如何在 Python 中打印这个输出?

我尝试了以下方法,但我坚持在每行的备用字符之间跳转。我正在寻找一个通用的解决方案,无论是一行还是两行或更多。

file=open('file.txt','r')
list1=[x.rstrip('\n') for x in file]
for i in list1:
    n=len(i)
    c=0
    while c<n:
        print(i[c],end=" ")
        c=c+1
    break

它只打印“ta”。

标签: python

解决方案


oneliners 是否适合这种事情是有争议的,但 itertools 可以做到这一点。

>>> from itertools import chain
>>> with open('/path/to/file') as data:
...     # could be just data.readlines() if you don't mind the newlines
...     a, b = [l.strip() for l in data.readlines()]
>>> # a = "this is one"                                                                                                                  
>>> # b = "and my pen"
>>> ''.join(chain.from_iterable(zip(a, b))
'tahnids  miys  poenn'

我也不确定您的预期结果是否正确。如果您要交替所有字符,则两个空格应该在一起。

如果您的文件有两行以上,则替换a, b = ...lines = ...然后使用zip(*lines)应该适用于任何数字。

如果你想避免使用 itertools

''.join(''.join(x) for x in zip(a, b))

要包含所有字符,即使行的长度不同,您也可以再次使用 itertools。

from itertools import chain, zip_longest
''.join(chain.from_iterable(zip_longest(a, b, fillvalue='')))
# or
''.join(chain.from_iterable(zip_longest(*lines, fillvalue='')))

推荐阅读