首页 > 解决方案 > 将包含列表的列表转换为字符串

问题描述

我有这个清单:

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

标签: python

解决方案


您需要使用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; ...

推荐阅读