以前也有類似的問題,但這些解決方案對我的用例不起作用(例如,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