我正在使用2个标准对列表进行排序:
index_sort = {'r1':1, 'r2':2, 'T1':3, 'r3':4, 'T2':5, 'T3':6}
Eall_pairsorted = sorted(Eall_pairsorted, key = lambda e: (index_sort[e[0]], index_sort2[e[1]] ))
问题是我得到了:
['r1', 'r2', '++', '0.01 0.01', -56.19568267]
['r1', 'T1', '++', '0.01 0.017453292519943295', -56.19567285]
['r1', 'r3', '++', '0.01 0.01', -56.19568267]
['r1', 'T2', '++', '0.01 0.017453292519943295', -56.19567285]
['r1', 'T3', '++', '0.01 0.017453292519943295', -56.19568714]
['r2', 'T1', '++', '0.01 0.017453292519943295', -56.19567439]
['r2', 'r3', '++', '0.01 0.01', -56.19568267]
['r2', 'T2', '++', '0.01 0.017453292519943295', -56.1956784]
['r2', 'T3', '++', '0.01 0.017453292519943295', -56.19568357]
['T1', 'T2', '++', '0.017453292519943295 0.017453292519943295', -56.19566509]
['T1', 'T3', '++', '0.017453292519943295 0.017453292519943295', -56.19570279]
['r3', 'T1', '++', '0.01 0.017453292519943295', -56.1956784]
['r3', 'T2', '+-', '0.01 0.017453292519943295', -56.19567944]
['r3', 'T3', '++', '0.01 0.017453292519943295', -56.19568357]
['r3', 'T3', '--', '0.01 0.017453292519943295', -56.19568081]
['r3', 'T3', '+-', '0.01 0.017453292519943295', -56.19569063]
['r3', 'T3', '-+', '0.01 0.017453292519943295', -56.1956905]
['T2', 'T3', '++', '0.017453292519943295 0.017453292519943295', -56.19570279]
['T2', 'T3', '--', '0.017453292519943295 0.017453292519943295', -56.19570039]
['T2', 'T3', '+-', '0.017453292519943295 0.017453292519943295', -56.195661]
['T2', 'T3', '-+', '0.017453292519943295 0.017453292519943295', -56.19566132]
我希望将r3和T1切换成一行:
['r3', 'T1', '++', '0.01 0.017453292519943295', -56.1956784]
获得以下顺序:
['T1', 'r3', '++', '0.01 0.017453292519943295', -56.1956784]
我只想换掉T1'和' r3',而不是整个专栏。
任何提示如何操作?
答案 0 :(得分:0)
你不能在排序的同时做到这一点,但事后你可以这样做:
Eall_pairsorted = sorted(Eall_pairsorted, key = lambda e: (e[0], e[1]))
Eall_pairsorted = [[e[1], e[0]] + e[2:] for e in Eall_pairsorted]
测试:
>>> Eall_pairsorted = [
... ['r1', 'r2', '++', '0.01 0.01', -56.19568267],
... ['r1', 'T1', '++', '0.01 0.017453292519943295', -56.19567285],
... ['r1', 'r3', '++', '0.01 0.01', -56.19568267]
... ]
>>> Eall_pairsorted = [[e[1], e[0]] + e[2:] for e in Eall_pairsorted]
>>> Eall_pairsorted
[
['r2', 'r1', '++', '0.01 0.01', -56.19568267],
['T1', 'r1', '++', '0.01 0.017453292519943295', -56.19567285],
['r3', 'r1', '++', '0.01 0.01', -56.19568267]
]
答案 1 :(得分:0)
在这种特定情况下,您是否只想重新排列列表中的前两个元素?或者你想在这里应用哪种一般规则?我认为你应该澄清你的问题。如果只有一个特定案例困扰您,则以下内容将起作用。
使用列表理解:
lst = [
['r1', 'r2', '++', '0.01 0.01', -56.19568267],
['r3', 'T1', '++', '0.01 0.017453292519943295', -56.19567285],
['r1', 'r3', '++', '0.01 0.01', -56.19568267]]
lst = [['T1', 'r3'] + x[2:] if x[0:2] == ['r3', 'T1'] else x for x in lst]
没有列表理解:
Eall_pairsorted = [
['r1', 'r2', '++', '0.01 0.01', -56.19568267],
['r3', 'T1', '++', '0.01 0.017453292519943295', -56.19567285],
['r1', 'r3', '++', '0.01 0.01', -56.19568267]]
for index, item in enumerate(Eall_pairsorted):
if item[0:2] == ['r3', 'T1']:
Eall_pairsorted[index][0:2] = ['T1', 'r3']