在链接和分组列表列表时反转子列表

时间:2015-07-29 17:02:08

标签: python python-3.x

我有这个清单:

nodes = [
    ["630505499", "630507607"], 
    ["630507607", "633597294"], 
    ["630512154", "633597294"],  # needs to be flipped before grouping
    ["630512154", "630512151"]
]

想要这个结果:

["630505499", "630507607", "633597294", "630512154", "630512151"]

现在,我只有在没有任何需要翻转时才能运作的东西:

[x[0] for x in itertools.groupby(itertools.chain(*nodes))]

3 个答案:

答案 0 :(得分:2)

我认为你想要一个OrderedDict和链,OrderedDict会在保留顺序的同时删除欺骗:

import itertools
from collections import OrderedDict
print(list(OrderedDict.fromkeys(itertools.chain(*nodes)).keys()))

['630505499', '630507607', '633597294', '630512154', '630512151']

我不知道groupby如何真正适合你想要做的事情。

答案 1 :(得分:1)

我认为您只想展平列表并仅保留唯一值,例如 -

>>> nodes = [
...     ["630505499", "630507607"],
...     ["630507607", "633597294"],
...     ["630512154", "633597294"],  # needs to be flipped before grouping
...     ["630512154", "630512151"]
... ]
>>> newnodes = []
>>> for i in (y for x in nodes for y in x):
...     if i not in newnodes:
...             newnodes.append(i)
>>> newnodes
['630505499', '630507607', '633597294', '630512154', '630512151']

答案 2 :(得分:0)

因为当你在尾巴中放置元素时你必须翻转列表。 head未匹配,以下是OrderedDict提及Padraic Cunningham的示例代码。

from collections import OrderedDict                                                                           

 nodes = [                                                                      
     ["630505499", "630507607"],                                                
     ["630507607", "633597294"],                                                
     ["630512154", "633597294"],  # needs to be flipped before grouping         
     ["630512154", "630512151"]                                                 
]                                                                              

def f(x, y):                                                                   
     return x + (y if x[-1] == y[0] else y[::-1])                               

print list(OrderedDict.fromkeys(reduce(f, nodes)).keys())