是否可以将列表字典组合成一个列表?

时间:2016-07-06 11:26:04

标签: python dictionary

说我有这样的字典:

my_list = {
    "foo": ["a", "b", "c"],
    "bar": ["d", "e", "f"]
}

如何将此字典中的所有列表合并为一行代码中的一个大型列表(意味着不会有临时变量)?我提出了以下解决方案,但它不是很优雅:

def combine_list_dictionary():
    temp = []
    for (key, value_list) in my_list:
        temp += value_list
    return temp

combine_list_dictionary()  # ["a", "b", "c", "d", "e", "f"]

我不介意在此过程中密钥丢失。

3 个答案:

答案 0 :(得分:2)

请勿使用sum加入列表。关于python ideas邮件列表的讨论很长,为什么这是一个坏主意(稍后会得到链接)。

itertools.chain是一个很好的解决方案,或者如果您更愿意使用

>>> my_list = {
...     "foo": ["a", "b", "c"],
...     "bar": ["d", "e", "f"]
... }
>>> import operator as op
>>> reduce(op.concat, my_list.values())
['a', 'b', 'c', 'd', 'e', 'f']
>>>

以下是小型和大型词典的chainreduce之间的效果比较。

>>> import random
>>> dict_of_lists = {k: range(random.randint(0, k)) for k in range(0, random.randint(0, 9))}
>>> %timeit list(itertools.chain.from_iterable(my_list.values()))
The slowest run took 12.72 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 995 ns per loop
>>> %timeit reduce(op.concat, my_list.values())
The slowest run took 19.77 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 467 ns per loop

reduce大约是itertools的两倍。大型结构也是如此。

>>> dict_of_lists = {k: range(random.randint(0, k)) for k in range(0, random.randint(0, 9999))}
>>> %timeit list(itertools.chain.from_iterable(my_list.values()))
The slowest run took 6.47 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1 µs per loop
>>> %timeit reduce(op.concat, my_list.values())
The slowest run took 13.68 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 425 ns per loop

答案 1 :(得分:1)

您可以使用with open("C:/abproject.build", "r+") as script, open ("C:/tempfile.build","w+") as newscript: abproject = ("C:/abproject.build") for line in abproject.readlines(): if line == "@AppIdentifier@" : newabproject.write('"' + "AppIdentifier : " + '"' + appIdentifier.get() + '"' + "\n") else: newabproject.write(line) abproject.close() newabproject.close() os.remove("abproject.txt") os.remove("tempfile.buil","abproject.txt")

itertools

答案 2 :(得分:0)

这应该做:

result = sorted(sum(my_list.values(), []))

如果您的结果不需要排序

,请删除sorted