将字典<str,list>展平为综合列表

时间:2019-09-30 17:44:50

标签: python python-3.x

因此我从服务器请求中获得了以下字典:

dict = {"first": "Mark", "last": "Zuckerberg", "alternative": ["Zuck", "Facebook guy"]}

我希望将其转换为这样的列表:

result = ["Mark", "Zuckerberg", "Zuck", "Facebook guy"]

我真的想让它保持pythonic以获得个人满意。我最近去过的地方是这个,您可以告诉它只给了我嵌套列表,而不是我实际要查找的列表。

values = list(dict.values())
result = [item for sublist in values for item in sublist if isinstance(sublist, list)]

感谢您的任何输入。

1 个答案:

答案 0 :(得分:7)

您可以这样做:

def flatten(s):
    for e in s:
        if isinstance(e, (tuple, list)):
            yield from flatten(e)
        else:
            yield e


d = {"first": "Mark", "last": "Zuckerberg", "alternative": ["Zuck", "Facebook guy"]}

result = list(flatten(d.values()))

print(result)

输出

['Mark', 'Zuckerberg', 'Zuck', 'Facebook guy']

flatten函数将处理任意嵌套列表。