Convert list of lists to delimited string

感情迁移 提交于 2021-02-16 00:34:15

问题


How do I do the following using built-in modules only?

I have a list of lists like this:

[['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]

And from it, I'd like to produce a string representation of a table like this where the columns are delimited by tabs and the rows by newlines.

dog 1
cat 2   a
rat 3   4
bat 5

i.e.

'dog\t1\ncat\t2\ta\nrat\t3\t4\nbat\t5'

回答1:


Like this, perhaps:

lists = [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]
result = "\n".join("\t".join(map(str,l)) for l in lists)

This joins all the inner lists using tabs, and concatenates the resulting list of strings using newlines.

It uses a feature called list comprehension to process the outer list.




回答2:


# rows contains the list of lists
lines = []
for row in rows:
    lines.append('\t'.join(map(str, row)))
result = '\n'.join(lines)


来源:https://stackoverflow.com/questions/898391/convert-list-of-lists-to-delimited-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!