将Dict项添加到列表中,并将具有相同键的值附加到较新的列表项中

时间:2019-02-11 13:07:37

标签: python dictionary collections

我具有以下实现方式:

from collections import defaultdict
from collections import OrderedDict

prod = [
    [1, 'tomato', 'veg', 'Jan-1'],
    [1, 'banana', 'fruit', 'Jan-3'],
    [2, 'melon', 'fruit', 'Jan-2'],
    [3, 'apple', 'fruit', 'Jan-4'],
    [2, 'cucumber', 'veg', 'Jan-1']
]

d = defaultdict(list)

for i in range (0, len(prod)):
    f_name = prod[i][1]
    f_type = prod[i][2]
    f_date = prod[i][3]

    key = prod[i][0]

    d[key].append([f_name, f_type, f_date])

e = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
print ("***************")
print (e)

table_for_graph = []

for key, value in e.iteritems():
    table_for_graph.append(value)

print (table_for_graph)

我得到的输出是这样的:

[[['tomato', 'veg', 'Jan-1'], ['banana', 'fruit', 'Jan-3']], [['melon', 'fruit', 'Jan-2'], ['cucumber', 'veg', 'Jan-1']], [['apple', 'fruit', 'Jan-4']]]

我想创建一个这样的列表:

[
    ['tomato''\n''banana','veg''\n''fruit','Jan-1''\n''Jan-3'],
    ['melon''\n''cucumber','fruit''\n''veg','Jan-2''\n''Jan-1'],
    ['apple','fruit','Jan-4']
]

意思是,我想串联具有相同密钥的项目。 我该怎么办?我还不知道如何迭代thorugh dict。

1 个答案:

答案 0 :(得分:1)

对于初学者来说,构造字典的循环可以大大简化,因为拆包和重新打包是多余的,除非您需要重新排序元素

x = [1, 0, 0, 1, 1, 1, 0, 0, 0, 0]
x_remove = [1, 4, 5]

for index,value in enumerate(x):
    for remove_index in x_remove:
        if(index == remove_index-1):
            x[index] = ""

final_list = [final_value for final_value in x if(final_value != "")]
print(final_list)

第二,for item in prod: d[item[0]] = item[1:] 最初完全不需要循环:

table_graph

这里的每个项目都是一个嵌套列表,例如:

table_for_graph = e.values()

您可以通过将位压缩在一起来有效地转置它:

>>> e[1]
[['tomato', 'veg', 'Jan-1'],
 ['banana', 'fruit', 'Jan-3']]

将它们放在一起:

>>> zip(*e[1])
[['tomato', 'banana'],
 ['veg', 'fruit'],
 ['Jan-1', 'Jan-3']]

您可以在字典的每个元素上运行该表达式:

 >>> [s in line for line in zip(*e[1]) for s in line]
 ['tomato', 'banana', 'veg', 'fruit', 'Jan-1', 'Jan-3']