将2个列表合并为1,这是“词典”中的值

时间:2016-09-25 12:10:23

标签: python python-2.7 python-3.x

大家好,我对编程很新。

我有一个dictC

dictC = {' a':[1,2,3,4,5],' b':[5,6,7,8,9,10]}

我希望我的输出像

mergedlist = [1,2,3,4,5,6,7,8,9,10]

任何人都可以帮助我定义一个函数的逻辑吗?

我尝过这样的事情

在这里输入代码 dictC = {&#39; a&#39;:[1,2,3,4,5,6,7],&#39; b&#39;:[3,7,8,9,10]} < / p>

result = MergeDictValues(dictC)

print result

dictC = {&#39; a&#39;:[1,2,3,4,5,6,7],&#39; b&#39;:[3,7,8,9,10 ]}     dictc =(dictC.values())

dictc.extend(dictc)

print dictc

def MergeDictValues(inputDict):     resultList = []     mergedList =#我在这里错过了我的逻辑     mergedList.extend() return resultList()

MergeDictValues(dictc)

resultList= MergeDictValues(dictc)

print resultList

3 个答案:

答案 0 :(得分:0)

mergedlist = dictC['a']+ dictC['b']

编辑 - 等待 - 你知道列表中有重复的元素(列表1的最后一个元素是5,但列表2的第一个元素也是如此) - 这是数据的不变特征。我需要更多信息..

答案 1 :(得分:0)

def MergeDictValues(dictC):
    return [x for y in dictC.values() for x in y]

输入:

dictC = {'a':[1,2,3,4,5],'b':[5,6,7,8,9,10]}
MergeDictValues(dictC)

Out put:

[1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10]

答案 2 :(得分:0)

Pythons dicts是无序的。如果迭代键,则应首先对它们进行排序。否则你可能会得到[5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5]

你可以使用双列表理解:

dictC = {'a':[1,2,3,4,5],'b':[5,6,7,8,9,10]}
print([x for key in sorted(dictC) for x in dictC[key]])
# [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10]

sum添加列表:

print(sum([dictC[key] for key in sorted(dictC)], []))
# [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10]