将两行打印为单行,但每个源的字符都是交替的

2024-04-26 21:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有文件.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”。你知道吗


Tags: and文件intxtforismythis
1条回答
网友
1楼 · 发布于 2024-04-26 21:04:10

OneLiner是否适合这类应用还存在争议,但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'

我也不确定你的预期结果是否正确。如果你交替使用所有字符,两个空格应该在一起。你知道吗

如果文件有两行以上,则用lines = ...替换a, b = ...,然后使用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='')))

相关问题 更多 >