【发布时间】:2019-07-22 08:37:09
【问题描述】:
我有一个列表列表,我想根据其子列表的值重新排列。
list = [["c","d"], ["b", "c"], ["a", "b"], ["x", "y"]]
最终产品应如下所示:
new_list = [["a", "b"], ["b", "c"], ["c", "d"], ["x", "y"]]
Python 代码应该分析list 中的每个元素,并将它们重新排列成new_list。具有相同元素的子列表应并排放置,例如["b", "c"] 应放置在["a", "b"] 之后,形成["a", "b"], ["b", "c"] 的链。
这是我对列表进行排序的尝试:
for i in list:
if len(new_list) == 0:
new_list.append(i)
else:
for j in new_list:
if j[0] == i[1]:
newindex = new_list.index(j)
new_list.insert(newindex, i)
不幸的是,使用上面的代码,我得到了一个无限循环,它卡在 else 块中。
欢迎任何关于更好解决方案的建议。谢谢。
【问题讨论】:
-
一般来说,您不应该在迭代列表时修改列表的内容(插入/删除)。您还可以使用内置的
sorted和自定义按键功能。 -
不能只使用基本的 list.sort() 函数吗?我认为这会产生相同的结果?
-
您的排序顺序似乎未指定。如果你有子列表
[ "a"," b"], [ "a"," c"], [ "b","c"]? -
new_list应该是什么,例如list = [["b","m"], ["b","x"], ["b", "c"], ["a", "b"], ["x", "y"], ["m", "n"]]? (也就是说 - 不止一条路径)。 -
这可能有点类似于Topological Sort,加深了你想用并行路径做什么
标签: python list sorting sublist compare-and-swap