以前也有类似的问题,但这些解决方案对我的用例不起作用(例如,Making a flat list out of list of lists in Python和Flattening a shallow list in Python。我有一个字符串列表,并列出,其中嵌入列表还可以包含字符串,并列出我想要把它变成一个简单的字符串列表而不分割字符串转换为字符的列表在Python中展开字符串列表和字符串列表以及列表
import itertools
list_of_menuitems = ['image10', ['image00', 'image01'], ['image02', ['image03', 'image04']]]
chain = itertools.chain(*list_of_menuitems)
结果列表:
['i', 'm', 'a', 'g', 'e', '1', '0', 'image00', 'image01', 'image02', ['image03', 'image04']]
预期结果:
['image10', 'image00', 'image01', 'image02', 'image03', 'image04']
什么是最好的(Pythonic)的方式来做到这一点?
参见:http://stackoverflow.com/questions/16176742/python-3-replacement-for-deprecated-compiler-ast-flatten-function –
我同意它几乎是http://stackoverflow.com/questions/5286541/how-can-i-flatten-lists-without-splitting-strings的重复。这个问题中缺少的一个方面(在提问之前我没有找到)是任意级别的嵌套问题。然而,解决方案张贴在那里(和在http:// stackoverflow。com/questions/16176742/python-3-replacement-for-deprecated-compiler-ast-flatten-function)至少在我提供的情况下可以很好地处理这个问题。 –
OP:使用'basestring'而不是'str',这样你就不会分裂'unicode'。 – 2rs2ts