在Python中转置List中的字符串
我想问是否可以“转置”字符串列表。例如,我的输入是:
x = ["___", "aaa", "---", "bbb", "---", "ccc", "___"]
for i in x:
print (i)
_______
*a*a*a*
-------
*b*b*b*
-------
*c*c*c*
_______
我想将此字符串列表转置为以下输出: (只有字母会移动,但行分隔符除外。)
_______
*c*b*a*
-------
*c*b*a*
-------
*c*b*a*
_______
I would like to ask if it is possible to "transpose" a list of strings. For example, my inputs are:
x = ["___", "aaa", "---", "bbb", "---", "ccc", "___"]
for i in x:
print (i)
_______
*a*a*a*
-------
*b*b*b*
-------
*c*c*c*
_______
I would like to transpose this list of strings into the following output:
(Only the letters will shift but the line seperator.)
_______
*c*b*a*
-------
*c*b*a*
-------
*c*b*a*
_______
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
类似于:
输出:
reversed
是为了得到cba
而不是abc
,后者是从另一个角转置的。一些解释:
切片(
1::2
,即从1
的第二个元素开始,以2
为步长)用于仅替换文本,保留行。它还用于仅选择解决方案所需的数据。通过压缩解包列表,执行“转置”。添加反转:
这里的结果是元组,但这并不重要,因为无论如何您都需要将所有内容转回字符串:
将所有内容放在一起,您将得到上面提供的解决方案。
编辑:你改变了问题,但实际上更多的是相同的。如果您无法弄清楚,请再仔细阅读上面的内容,因为所有部分或多或少都在那里。它变得有点棘手,因为您现在还需要对字符串执行切片和更新,并且它不再是一行。但同样的想法 - 如果这是家庭作业,请尝试完成它,因为不完成它可能会在以后反咬你一口。
输出:
Something like:
Output:
The
reversed
is there to getcba
instead ofabc
, which would be the transposed from the other corner.A bit of explanation:
The slice (
1::2
i.e. starting at the 2nd element with1
, in steps of2
) is used to replace only the text, and leave the lines. It's also used to select only the data that's needed for the solution.By zipping the unpacked lists, the 'transpose' is performed. Adding the reversal:
The results here are tuples, but that doesn't matter, since you need everything turned back into strings anyway:
All put together, you get the solution provided above.
Edit: you changed the problem, but it's really more of the same. If you weren't able to figure it out, have another close read of the above, because all the parts are more or less there. It gets a bit trickier because you now need to perform the slice and update on strings as well, and it's no longer a single line. But the same idea - if this was homework, try to get it, because not getting it might come back to bite you later.
Output: