如何在python中合并上一个/下一个列表?

2024-06-16 12:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有正好两个上一个下一个项目的列表。你知道吗

[['Robert','Christopher'],['John','Eric'],['Mark','John'],['Mickael','Robert']]

对于第一个列表,“Robert”是上一个,而“Christopher”是下一个。你知道吗

我想通过保持最终列表的连续性来合并具有最低上一个和最高下一个的列表。 结果可以是:

[['Mickael','Christopher'],['Mark','Eric']]

或者

[['Mark','Eric'],['Mickael','Christopher']]

结果是两个列表,因为这两个列表之间没有连续性。 上一个和下一个不能排序(例如'Mickael'在'Christopher'之前)。没有循环,也没有重复的元素(即“Robert”总是在“Christopher”之前,“John”总是在“Eric”之前…),所以这是一个拓扑图

在python中很容易实现吗?


Tags: 项目元素列表排序johnrobertmarkeric
2条回答

基于How can I order a list of connectionsAshwini Chaudhary的链接(thx Ashwini),我编写了一个适合我需要的解决方案:

items= [['F','G'], ['B','C'], ['A','B'], ['C','D'], ['E','F']]
mydict = dict(items)
for prev,next in items:
    if next in mydict:
        mydict[prev] = mydict[next]
        del mydict[next]
print(list(mydict.items()))

结果是:

[('A', 'D'), ('E', 'G')]

我认为这会奏效,而且效率很高:

items = [['A','B'], ['B','C'], ['C','E'], ['E','F'], ['F','G']]
nodes = dict(items)
changed = True
while changed:
    changed = False
    keys = nodes.keys()
    for prevEl in keys:
        if not prevEl in nodes: #may have been deleted
            continue
        nextEl = nodes[prevEl]
        if nextEl in nodes:
            tmp = nodes[nextEl]
            del nodes[nextEl]
            nodes[prevEl] = tmp
            changed = True

相关问题 更多 >