python - 按连续顺序对元组列表进行排序

标签 python list python-3.x

我想按连续顺序对元组列表进行排序,因此每个元组的第一个元素等于前一个元组的最后一个元素。

例如:

input = [(10, 7), (4, 9), (13, 4), (7, 13), (9, 10)]
output = [(10, 7), (7, 13), (13, 4), (4, 9), (9, 10)]

我开发了这样的搜索:

output=[]
given = [(10, 7), (4, 9), (13, 4), (7, 13), (9, 10)]
t = given[0][0]
for i in range(len(given)):
      # search tuples starting with element t
      output += [e for e in given if e[0] == t]
      t = output[-1][-1] # Get the next element to search

print(output)    

是否有 pythonic 方法来实现这样的顺序? 以及“就地”执行此操作的方法(仅使用列表)?

在我的问题中,输入可以使用所有元组以循环方式重新排序,因此选择第一个元素并不重要。

最佳答案

假设 list 中的元组是循环的,您可以使用 dictO(n) 的复杂度内实现它:

input = [(10, 7), (4, 9), (13, 4), (7, 13), (9, 10)]
input_dict = dict(input)  # Convert list of `tuples` to dict

elem = input[0][0]  # start point in the new list

new_list = []  # List of tuples for holding the values in required order

for _ in range(len(input)):
    new_list.append((elem, input_dict[elem]))
    elem = input_dict[elem]
    if elem not in input_dict:
        # Raise exception in case list of tuples is not circular
        raise Exception('key {} not found in dict'.format(elem))

new_list 持有的最终值将是:

>>> new_list
[(10, 7), (7, 13), (13, 4), (4, 9), (9, 10)]

关于python - 按连续顺序对元组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41221428/

相关文章:

python - 类型对象 'x' 没有属性过滤器

python - 如何检查字典是否有某个键(Python)

python - 通过 API (Python) 将多个视频添加到 youtube-playlist

list - SML - 查找列表中的出现次数以形成有序对

list - 在具有键 "Oranges"的映射列表中查找所有值

python - 在单元测试中比较 numpy float 数组

python - 如何获取系列中的索引?

python - 当满足特定条件时无法显示另一个 tkinter 框架

python-3.x - 解决环境 : | Found conflicts! 寻找不兼容的包。更新是永恒的

python - 未从 PyPDF2 上的正则表达式接收 PDF 的正确模式