展平字符串列表以及Python中的字符串列表和列表 [英] Flatten a list of strings and lists of strings and lists in Python

查看:94
本文介绍了展平字符串列表以及Python中的字符串列表和列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前也曾提出过类似的问题,但是这些问题的解决方案不适用于我的用例(例如,在Python中平铺浅表.我有一个字符串和列表的列表,其中嵌入式列表也可以包含字符串和列表,我想将其转换为一个字符串和列表.简单的字符串列表,而无需将字符串拆分为字符列表.

Similar questions have been asked before, but the solutions to those don't work for my use case (e.g., Making a flat list out of list of lists in Python and Flattening a shallow list in Python. I have is a list of strings and lists, where embedded list can also contain strings and lists. I want to turn this into a simple list of strings without splitting strings into list of characters.

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)是什么?

What's the best (Pythonic) way to do this?

推荐答案

经常重复的

The oft-repeated flatten function can be applied to this circumstance with a simple modification.

from collections import Iterable
def flatten(coll):
    for i in coll:
            if isinstance(i, Iterable) and not isinstance(i, basestring):
                for subc in flatten(i):
                    yield subc
            else:
                yield i

basestring将确保strunicode对象均未拆分.

basestring will make sure that both str and unicode objects are not split.

还有一些依靠i而不具有__iter__属性的版本.我对此一无所知,因为我认为str现在具有该属性.但是,值得一提.

There are also versions which count on i not having the __iter__ attribute. I don't know about all that, because I think that str now has that attribute. But, it's worth mentioning.

(请对链接的答案进行投票.)

(Please upvote the linked answer.)

这篇关于展平字符串列表以及Python中的字符串列表和列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆