python - 将包含列表的列表转换为字符串
问题描述
我有这个清单:
l = [['a', ['b'], 'c', 'd', 'e'], ['f', ['g'], 'h', 'i', 'j'], ['k', 'l', 'n', 'o', 'p'], ['q', ['r'], 's', 't', 'u']]
我想把它转换成这个字符串:
a;b;c;d;e;f;g;h;i .....
我试过这样做:
flat_list = [item for sublist in l for item in sublist]
return flat_list
解决方案
您需要使用str.join
,首先加入内部列表的元素,&
然后加入外部列表\n
:
out = '\n'.join(';'.join(','.join(e) if type(e) is list else e for e in s) for s in l)
print(out)
输出:
Holding Out;Bonnie Tyler;Secret Dreams and Forbidden Fire;Country-Pop-Rock;5:50
Poker Face;Lady Gaga;The Fame;Pop;3:59
Another One Bites the Dust;Queen;The Game;Funk rock;3:36
Nothing Else Matters;Metallica;Metallica;Rock-Heavy metal;6:29
请注意,当艺术家是一个列表时,我已将其与,
. 因此,例如,当一个曲目上有多个艺术家时['Billy Joel', 'Ray Charles']
,他们将在列表中显示为
... ;Billy Joel,Ray Charles; ...
推荐阅读
- neo4j - 将一个标签的“属性键”合并到另一个标签中
- jpa - 集成 Java EE 7、Spring Security 和 EclipseLink 的问题
- amazon-web-services - 在 AWS RHEL 7.6 实例上安装 SCL
- c++ - 多线程 Monte Carlo pi 计算会因更多线程而失去精度?
- odoo - Odoo 11 工人
- python - 如何将列表的元素作为 np.where() 中的条件?
- java - 在 Spring Boot jar 中解压球衣库
- javascript - 如何修复 Promise 解决 win.loadFile() 和 app.on('browser-window-created') 事件之间的竞争条件
- c# - 如何使用 SQL Server 身份验证从 Web 服务远程访问 SQL Server 命名实例
- python - 在 Apache Zeppelin 上使用 anaconda 时出现“java.lang.RuntimeException: Failed to execute `conda info` exited with 1”