繁体   English   中英

以列表/字典理解方式合并列表

[英]combine lists in list/dict comprehension way

是否可以将列表/词典理解应用于以下代码以使["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] ,那么列表中的列表变平了 所以

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

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

如果所需列表中的值顺序很重要,则实现此目的的通用方法是根据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']

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

>>> 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() [tk[i] for i in tk]tk.values()完全相同。 因此,您可以建议的解决方案[x for t in tk.values() for x in t]与您所获得的等效,只是一行。

考虑到您手动选择键序列的约束:

>>> 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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM