因此我从服务器请求中获得了以下字典:
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)]
感谢您的任何输入。
答案 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
函数将处理任意嵌套列表。