如何将键控2列表的列表转换为相同键控N列表的列表?

时间:2018-08-23 19:24:16

标签: python

如何创建以第一个元素为键的列表列表:

发件人:

myList = [ [26, 'hello'], [26, 'hola'], [26, 'hi'], [26, 'bonjour'], [27, 'bye'],[27, 'doei'], [27, 'see you'], [27, 'tot ziens'] ]

收件人:

[ [26, 'hello', 'hola', 'hi', 'bonjour'], [27, 'bye', 'doei', 'see you', 'tot ziens'] ]

5 个答案:

答案 0 :(得分:5)

由于要对键的值进行分组,因此它可能不是您要查找为输出的list,而是dict。稍后将允许进行恒定时间查找。

myList = [[26, 'hello'], [26, 'hola'], [26, 'hi'], [26, 'bonjour'],
          [27, 'bye'], [27, 'doei'], [27, 'see you'], [27, 'tot ziens']]

myDict = {}

for k, v in myList:
    myDict.setdefault(k, []).append(v)

print(myDict)

输出

{26: ['hello', 'hola', 'hi', 'bonjour'], 27: ['bye', 'doei', 'see you', 'tot ziens']}

尽管如果您绝对需要一个列表列表,则可以像这样获得它:

# Only valid in Python3, use [k] + v in Python2
listOfLists = [[k, *v] for k, v in myDict.items()]

print(listOfLists)

输出

[[26, 'hello', 'hola', 'hi', 'bonjour'], [27, 'bye', 'doei', 'see you', 'tot ziens']]

答案 1 :(得分:0)

使用itertools.groupby和列表理解

>>> from itertools import groupby
>>> from operator import itemgetter
>>> myList = [ [26, 'hello'], [26, 'hola'], [26, 'hi'], [26, 'bonjour'], [27, 'bye'],[27, 'doei'], [27, 'see you'], [27, 'tot ziens'] ]
>>> [[k] + [e[1] for e in grps] for k,grps in groupby(myList, itemgetter(0))]
[[26, 'hello', 'hola', 'hi', 'bonjour'], [27, 'bye', 'doei', 'see you', 'tot ziens']]

答案 2 :(得分:0)

我建议您使用此解决方案,该解决方案尚未优化,但易于阅读:

from collections import defaultdict

myList = [ [26, 'hello'], [26, 'hola'], [26, 'hi'], [26, 'bonjour'], [27, 'bye'],[27, 'doei'], [27, 'see you'], [27, 'tot ziens'] ]

d = defaultdict(list)
for [k,v] in myList:
     d[k].append(v)
newList = [[k,*v] for k,v in d.items()]

print(newList)  # [[26, 'hello', 'hola', 'hi', 'bonjour'], [27, 'bye', 'doei', 'see you', 'tot ziens']]

答案 3 :(得分:0)

这使用嵌套的理解:

[[y, *[x[1] for x in myList if x[0]==y]] for y in set([z[0] for z in myList])]

输出:

[[26, 'hello', 'hola', 'hi', 'bonjour'], [27, 'bye', 'doei', 'see you', 'tot ziens']]

答案 4 :(得分:-1)

最有效的方法是将相似的项目与itertool.groupby组合在一起。分组之前,必须使用将用于分组的相同键对列表进行排序。

from itertools import groupby

[([key] + [word for _, word in words]) for key, words 
   in groupby(sorted(myList), key=lambda x: x[0])]
#[[26, 'bonjour', 'hello', 'hi', 'hola'], 
# [27, 'bye', 'doei', 'see you', 'tot ziens']]

顺便说一句,列表没有键。 (但是字典是这样的。)