2017-07-25 96 views
0
串混合

比方说有是有弦与名单混合的字典:嵌套列表理解与用条件

dictionary = {'item_a': 'one', 
       'item_b': 'two', 
       'item_c': ['three', 'four'], 
       'item_d': 'five'} 

,其结果应该是:

['one', 'two', 'three', 'four', 'five'] 

它如何可以实现通过使用列表理解?

下面给出了仅用于列表中的值,但它缺少不在列表中的字符串和其他不工作,如果加权后,如果:

[val for sublist in dictionary.values() if type(sublist) is list for val in sublist] 
+0

我想答案你可能正在寻找可以在这里找到:https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – Fallenreaper

+0

可能的重复[制作一个简单的列表从Python列表中删除列表](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – Fallenreaper

+1

你将会遇到问题,因为字典是无序的数据结构。 – GWW

回答

2

这工作,但它不是漂亮。如果子列表不是一个列表,它将它变成一个元素列表。

[val for sublist in dictionary.values() for val in (sublist if type(sublist) is list else [sublist])] 
2

一种方法是将所有的值正常化iterables和使用intertools.chain的结果,如

from itertools import chain 

list(chain(*(v if isinstance(v, list) else (v,) for v in dictionary.values())) 

这样做什么是所有非列表转换成元组结合(例如迭代)然后使用链来组合所有的迭代,最后列出来为你提供一个列表。

如果您不想重复,请使用set而不是列表。

0

我不知道如何有用的是这样的,但是,如果你坚持在压缩格式尝试有它:

[m for n in [[i] for i in dictionary.values() if not list(i)==i ]+[i for i in dictionary.values() if list(i)==i ] for m in n] 

您将获得:

['one', 'two', 'five', 'three', 'four']