Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表的顺序应用于其他列表_Python_List_Python 2.7 - Fatal编程技术网

Python 将列表的顺序应用于其他列表

Python 将列表的顺序应用于其他列表,python,list,python-2.7,Python,List,Python 2.7,我有一份清单,有具体的顺序: L = [1, 2, 5, 8, 3] 以及一些包含主列表元素但顺序不同的子列表: L1 = [5, 3, 1] L2 = [8, 1, 5] 如何将L的顺序应用于L1和L2 例如,处理后的正确顺序应为: L1 = [1, 5, 3] L2 = [1, 5, 8] 我正在尝试类似的方法,但我正在努力以正确的顺序设置新列表 new_L1 = [] for i in L1: if i in L: print L.index(i) #get

我有一份清单,有具体的顺序:

L = [1, 2, 5, 8, 3]
以及一些包含主列表元素但顺序不同的子列表:

L1 = [5, 3, 1]
L2 = [8, 1, 5]
如何将
L
的顺序应用于
L1
L2

例如,处理后的正确顺序应为:

 L1 = [1, 5, 3]
 L2 = [1, 5, 8]
我正在尝试类似的方法,但我正在努力以正确的顺序设置新列表

new_L1 = []
for i in L1:
   if i in L: 
      print L.index(i) #get the order in L

看起来您只想根据值位于
L
中的索引对
L1
L2
进行排序

L = [1, 2, 5, 8, 3]

L1 = [5, 3, 1]
L2 = [8, 1, 5]

L1.sort(key = lambda x: L.index(x))
L2.sort(key = lambda x: L.index(x))

下面是使用列表理解进行排序的另一种方法:

>>> L = [1, 2, 5, 8, 3]
>>> 
>>> L1 = [5, 3, 1]
>>> L2 = [8, 1, 5]
>>> 
>>> L1 = [i for i in L if i in L1]
>>> L2 = [i for i in L if i in L2]
>>> 
>>> L1
[1, 5, 3]
>>> L2
[1, 5, 8]

或者干脆
key=L.index
。我对python不太熟悉,但无法想象这怎么能不减少排序时间,从
O(n*log(n))
O(n*n*log(n))
。如果是这样的话,它只适用于小列表。对于较大的列表,可能应该构建某种
O(1)
-查找字典,从元素到列表
L
中的索引。