在python中组合具有类似值的列表列表

时间:2013-12-02 22:56:21

标签: python python-2.7

我有一个列表列表,如下所示:

items = [['118', 'white'], ['118','Jack'], ['118','guilty'],  ['200','black'], ['200','mark'], ['200','not guilty']]

有没有办法使用for循环来获取每个列表中的第二个值并将其折叠到一个新列表中?

像这样:

['white', 'jack', 'guilty']
['black','mark','not guilty']

4 个答案:

答案 0 :(得分:2)

假设您的列表中的元素具有与示例中相同的键,您可以使用itertools.groupby()来有效地执行此操作:

>>> import itertools
>>> items = [['118', 'white'], ['118','Jack'], ['118','guilty'],  ['200','black'], ['200','mark'], ['200','not guilty']]
>>> [[x[1] for x in g] for k, g in itertools.groupby(items, lambda x: x[0])]
[['white', 'Jack', 'guilty'], ['black', 'mark', 'not guilty']]

您还可以使用operator.itemgetter(0)替代lambda x: x[0]

请注意,如果items不一定按其键分组元素,则可以在sorted(items)调用中使用items代替groupby(),这样就可以了。< / p>

这是一个保留密钥的版本:

>>> [(k, [x[1] for x in g]) for k, g in itertools.groupby(items, lambda x: x[0])]
[('118', ['white', 'Jack', 'guilty']), ('200', ['black', 'mark', 'not guilty'])]

您可以将此列表直接传递到dict()内置函数,以将其转换为字典。

答案 1 :(得分:1)

from collections import defaultdict
entries = defaultdict(list)
for (key, value) in items:
    entries[key].append(value)

现在entries是第二个值列表的字典。您可以通过键('118')获取它们,也可以使用values()获取列表列表。

答案 2 :(得分:0)

output_dict = {}
for each_key in items:
  for each_item in each_key:
    try:
      output_dict[each_key].append(each_item) #fails as I'm trying to use a list as a dict key
    except Exception as e:
      output_dict[each_key] = [] #see above
      output_dict[each_key].append(each_item) #see above
for each_list in output_dict:
  print(each_list)

正如Peter DeGlopper所指出的那样,这段代码很糟糕,我应该心疼。我已经对代码进行了评论,以指出我的错误。有更好的解决方案,但只是纠正我的错误:

items = [['118', 'white'], ['118','Jack'], ['118','guilty'],  ['200','black'], ['200','mark'], ['200','not guilty']]

output_dict = {}
for each_list in items:
  if each_list[0] not in output_dict: output_dict[each_list[0]] = list()
  output_dict[each_list[0]].append(each_list[1])

>>> for each_list in output_dict:
>>>  print(each_list)
['white','Jack','guilty']
['black','mark','not guilty']

答案 3 :(得分:0)

>>> k = set(x[0] for x in items)
>>> [ [x[1] for x in items if x[0] == key] for key in sorted(k) ]
[['white', 'Jack', 'guilty'], ['black', 'mark', 'not guilty']]