以list / dict理解方式组合列表

时间:2017-04-04 22:58:08

标签: python list-comprehension

是否可以将列表/字典理解应用于以下代码以使["abc", "ab", "cd"]

tk = {}
tk[1] = ["abc"]
tk[2] = ["ab", "cd"]
tk[3] = ["ef", "gh"]
t = (1, 2)
combined = []
combined.append(tk[i]) for i in t #does not work. note, not all tk values are used, this is based on t.

我能想到的 ll = [tk[i] for i in t],然后转为flatten list out of lists。所以

ll = [tk[i] for i in t]
[item for sublist in ll for item in sublist]

但这不是单行。我想知道是否有更好的方法。

3 个答案:

答案 0 :(得分:2)

如果所需列表中的值顺序很重要,实现此目的的一般方法是根据dict中的项目进行排序,并合并列表值。例如:

>>> from operator import itemgetter
>>> from itertools import chain

>>> list(chain.from_iterable(i for _, i in sorted(tk.items(), key=itemgetter(0))))
['abc', 'ab', 'cd']

答案 1 :(得分:2)

只需遍历字典的值即可。像这样:

>>> tk = {}
>>> tk[1] = ['abc']
>>> tk[2] = ['ab', 'cd']
>>> combined = [x for t in tk.values() for x in t]
>>> print combined
['abc', 'ab', 'cd']

如果您需要维护列表的顺序,甚至可以使用OrderedDict,因为常规dict不保证其键的顺序:

>>> import collections
>>> tk = collections.OrderedDict()
>>> tk[1] = ['abc']
>>> tk[2] = ['ab', 'cd']
>>> combined = [x for t in tk.values() for x in t]
>>> print combined
['abc', 'ab', 'cd']

请注意,您提出的[tk[i] for i in (1, 2)]将无法获得所需的结果。您仍然需要遍历每个列表中的值。

>>> [tk[i] for i in (1, 2)]
[['abc'], ['ab', 'cd']]

另请注意,[tk[i] for i in tk],正如您稍后提出的,与tk.values()完全相同。因此,您可以将建议的解决方案[x for t in tk.values() for x in t]等同于您在一行中所取得的成果。

答案 2 :(得分:1)

考虑到您手动选择一系列密钥的限制:

>>> tk = {}
>>> tk[1] = ["abc"]
>>> tk[2] = ["ab", "cd"]
>>> tk[3] = ["ef", "gh"]

你想:

>>> [vals for i in (1,2) for vals in tk[i]]
['abc', 'ab', 'cd']
相关问题