python - 将两行打印为单行,但每个源行中都有备用字符
问题描述
我有 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='')))
推荐阅读
- r - 通过 select 语句传递向量
- scala - 如何强制 sbt 使用与依赖项目兼容的 scalaVersion 来解决依赖关系
- spring - 当我想连接有这个问题“错误”:“内部服务器错误”,“消息”:“没有可用的消息”,
- git - 为 Git 分叉更新 go 资产路径
- html - 动态 V-for 显示没有结果(Vue.js)
- firebase - 为什么我的 DocumentSnapshot DocumentID 在我的数据库中返回 null?
- python - 是否有 python 函数来替换文本文件中特定列表中的特定索引?
- google-apps-script - 如何在 Google 表格中组合多个 onEdit/Trigger 脚本?
- time-complexity - 定义算法的时间复杂度(log n 或 n)
- python - 带有 NGINX proxy_pass 的烧瓶