我有文件.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"。
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)
应该适用于任何数字。
如果你想避免迭代工具
''.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='')))