我知道"".join(list)
将列表转换为字符串,但如果该列表包含嵌套列表会怎么样?当我尝试它时,由于意外的列表类型而返回TypeError
。我猜测错误处理是可能的,但到目前为止,我的尝试都没有结果。“”.join(list)如果列表在python中包含嵌套列表?
0
A
回答
4
好吧,如果列表嵌套,只需flatten事前:
>>> import itertools
>>> lst = [['a', 'b'], ['c', 'd']]
>>> ''.join(itertools.chain(*lst))
'abcd'
4
你可以尝试这样的事:
''.join(''.join(inner) for inner in outer)
这应该工作,不会有太多的麻烦如果外部列表包含其中的字符串和列表,''.join(myString) -> myString
。
0
你也可以试试这个片断:
from collections import Iterable
ellipsis = type('',(),{'__str__' : lambda self:'...'})()
def flatten(collection,stack = None):
if not stack: stack = set()
if id(collection) in stack:
yield ellipsis
return
for item in collection:
if isinstance(item,Iterable):
stack.add(id(collection))
for subitem in flatten(item,stack):
yield subitem
stack.remove(id(collection))
else: yield item
x = [1,2,[3,4,[5],[[6]],7]]
x.append(x)
>>> print(', '.join(map(str,flatten(x))))
1, 2, 3, 4, 5, 6, 7, ...
相关问题
- 1. 嵌套列表中的Python嵌套列表不包含循环
- 2. linq嵌套列表包含
- 3. Python - 嵌套列表
- 4. 嵌套列表python
- 5. Python嵌套列表
- 6. Python:“散列”嵌套列表
- 7. 的Python:在列表嵌套
- 8. Python:从列表中删除子列表(如果包含/不包含订单)
- 9. 包含嵌套列表的元组的列表理解
- 10. Python的 - 从嵌套列表列表
- 11. 检查字符串是否包含嵌套列表的值 - python
- 12. 如何处理包含多个列表的Json中的缺失嵌套列表
- 13. python嵌套列表过滤?
- 14. Python搜索嵌套列表
- 15. Python:合并嵌套列表
- 16. Python的嵌套列表
- 17. 打印嵌套列表 - Python
- 18. Python - 迭代嵌套列表
- 19. Python:嵌套列表理解
- 20. Python - 动态嵌套列表
- 21. python操作嵌套列表
- 22. Python比较嵌套列表
- 23. python嵌套列表解析
- 24. 的Python:嵌套列表
- 25. 在嵌套列表中列表分页
- 26. 在Python中嵌套列表排序
- 27. 在python 3中编辑嵌套列表
- 28. python在nltk中嵌套列表理解
- 29. 在python中转置嵌套列表
- 30. 在python中转置嵌套列表
http://stackoverflow.com/questions/716477/join-list-of-lists-in-python – 2012-03-07 18:46:53
@MДΓΓБДLL这么多的代表,也没有dup投票?今天已经没有投票权了? – phihag 2012-03-07 18:48:18
该命令用于连接字符串。如果列表中的对象不是字符串(例如列表,在您的示例中),您将不得不尝试将它们转换为字符串,如下面首先建议的那样。 – mohit6up 2012-03-07 18:54:31