python list反向并从第二个元素排序

时间:2015-03-19 12:58:42

标签: python list sorting reverse

我想要转换这样的列表:

[[x, [1,2,3]], [y, [2,3,4]], [z, 4]]

成为:

[[1, x], [2, [x,y]], [3, [x,y]], [4, z]]

...基本上将其转换为内外的",以便将最里面的列表中的数字分开,并将与它们相关联的字母收集到每个数字的列表中。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以使用defaultdict

相当直接地完成此操作
from collections import defaultdict

data = [['x', [1, 2, 3]], ['y', [2, 3, 4]], ['z', [4]]]

temp = defaultdict(list)

for k, s in data:
    for v in s:
        temp[v].append(k)

result = sorted(temp.items())
# [(1, ['x']), (2, ['x', 'y']), (3, ['x', 'y']), (4, ['y', 'z'])]

答案 1 :(得分:1)

您可以使用collections.defaultdict

>>> d=defaultdict(list)
>>> for k,v in l:
...       if isinstance(v,list):
...             for t in v:
...                    d[t].append(k)
...       else:
...                    d[v].append(k)
... 
>>> d
defaultdict(<type 'list'>, {1: ['x'], 2: ['x', 'y'], 3: ['x', 'y'], 4: ['y', 'z']})

答案 2 :(得分:0)

有点难以理解的列表理解:

in_list = ['x', [1, 2, 3]], ['y', [2, 3, 4]], ['z', [4]]
[[num, [sublist[0] for sublist in in_list if num in sublist[1]]] for num in sorted(list(set(num for sublist in in_list for num in sublist[1])))]

给出:

Out[218]: [[1, ['x']], [2, ['x', 'y']], [3, ['x', 'y']], [4, ['y', 'z']]]