Python:使用另一个列表顺序对列表进行排序,具有不同的长度,并且没有 'sorted'

标签 python list sorting plone

我来解释一下吧:
我处于无法使用 python 内置函数(如“排序”、“设置”)、无法声明方法、无法创建条件 (if) 以及无法创建循环的环境中,除了:

  • 可以调用方法(但每次只能调用一个方法,并将返回保存在另一个变量上

    foo python:item.sort(); #foo 变量采用 item.sort() 返回的值

    bar python:foo.index(x);

  • 并且可以理解列表

    [item['bla'] for item in foo]

...我认为这对这个问题没有帮助

我有一个“correct_order”列表,其值为:

correct_order = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

我有一个“messed_order”列表,其中包含以下值:

messed_order = [55, 1, 44, 3, 66, 5, 4, 7, 2, 9, 0, 10, 6, 8]

好吧,我必须重新排序“messed_order”列表,使用“correct_order”的索引作为基础。 correct_order 中未包含的其余项目的顺序无关紧要。

这样的事情会解决(同样,除了我不能使用循环):

for item in correct_order:
    messed_order[messed_order.index(item)], messed_order[correct_order.index(item)] = messed_order[correct_order.index(item)], messed_order[messed_order.index(item)]

然后会出现在我想要的“ordered_list”上:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 55, 66, 44]

那么,我该怎么做呢?

对于那些了解 zope/plone 的人,我在一个皮肤页面 (.pt) 上,它没有辅助 python 脚本(我认为这对皮肤页面是不可能的,只对浏览器页面是不可能的。如果是的,告诉我怎么做,我会做的)。

最佳答案

很难回答,因为不知道什么是允许的,什么是不允许的。但是这个 O(N^2) 的解决方案怎么样?

[x for x in correct_order if x in messed_order] + [x for x in messed_order if x not in correct_order]

关于Python:使用另一个列表顺序对列表进行排序,具有不同的长度,并且没有 'sorted',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3633288/

相关文章:

python - 如何将 PostgreSQL 的 "INSERT...ON CONFLICT"(UPSERT) 功能与 flask_sqlalchemy 一起使用?

python - 如何从读取的 csv 中重新计算每个类(class)的人数

python - "Double"迭代器和生成器函数

list - Ant 中使用列表的并行作业

python - 从用户输入动态生成列表

Android加载器,要走的路?

ios - 按两个值对 NSMutableArray 进行排序

mysql - 当未提供 ORDER BY 子句时,SQL 会反转某些查询的排序顺序

mysql - 基于两列或多列的代数对 MySql 中的行进行排序

python - 如果 len(list) 不能被 3 整除,则排除函数中的最后一项。 python 2.7.1