gpt4 book ai didi

python - 将两行打印成单行,但每个源代码行使用交替字符

转载 作者:太空宇宙 更新时间:2023-11-04 11:15:16 25 4
gpt4 key购买 nike

我的 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”。

最佳答案

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='')))

关于python - 将两行打印成单行,但每个源代码行使用交替字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57160669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com