列表以匹配另一个嵌套列表

时间:2015-11-19 16:47:06

标签: nested-lists

根据第一个

排序的第二个列表

[['E', 'E', 'C], ['B', 'C', 'A'], ['E', 'B', 'F'], ['D', 'F', 'E']]

2 个答案:

答案 0 :(得分:2)

ref_list = ['c','b','a']
# sort [1,2,3] according to ref_list... viz: ['c','a','b'] => [3,1,2]
ordering = sorted(range(len(ref_list)), key=lambda i: ref_list[i])
for j in range(len(list2)):
  list2[j] = [list2[j][i] for i in ordering]

答案 1 :(得分:0)

这是我制作的一些快速代码,它可以工作,但可能需要一些重构:

def getListIndexes(some_list):
    return [x for x in enumerate(some_list)]

list1 = [['C', 'B', 'A']]
list2 = [['C', 'E', 'E'], ['C', 'B', 'A'], ['F', 'B', 'E'], ['E', 'F', 'D']]

values_before_1 = getListIndexes(list1[0])
values_after_1 = getListIndexes(list(sorted(list1[0])))

mapping = dict.fromkeys(list(range(len(list1[0]))))
for item in values_before_1:
    before, then = [(item[0],x[0]) for i, x in enumerate(values_after_1) if item[1]==x[1]][0]
    mapping[then] = before

results = [[None, None, None] for l in range(len(list2))]
for i, item in enumerate(list2):
    values = getListIndexes(item)
    for j in range(len(item)):
        results[i][mapping[j]] = list2[i][j]

print "[*] list1 with content: {} has been sorted and now is like: {}\n".format(list1[0], sorted(list1[0]))
print "[*] list2 with content:\n\n{}\n".format(list2)
print "...has been sorted based on list1 sorting and now looks like this...\n"
print results

<强>输出:

[*] list1 with content: ['C', 'B', 'A'] has been sorted and now is like: ['A', 'B', 'C']

[*] list2 with content:

[['C', 'E', 'E'], ['C', 'B', 'A'], ['F', 'B', 'E'], ['E', 'F', 'D']]

...has been sorted based on list1 sorting and now looks like this...

[['E', 'E', 'C'], ['A', 'B', 'C'], ['E', 'B', 'F'], ['D', 'F', 'E']]