简体   繁体   English

当我尝试根据另一个嵌套列表对嵌套列表进行排序时,如何解决此错误?

[英]How can I solve this error that occurs when I try to sort a nested list based on another nested?

I tried to base my solutions on other questions asked here but they dont quite work.我试图将我的解决方案建立在此处提出的其他问题上,但它们不太奏效。

I have a nested list:我有一个嵌套列表:

s = [[[921, 640], [4007, 49], [4821, 40]],
     [[1270, 20], [1943, 393], [4821, 183]],
     [[1300, 95], [857, 641], [4821, 83]]]

I want to sort the values at index 0 in the nested based on the values of another nested list.我想根据另一个嵌套列表的值对嵌套中索引 0 处的值进行排序。 The other list looks like this:另一个列表如下所示:

i = [[921, 4281, 4007], [1943, 1270, 4821], [4821, 1300, 857]]

As you can see the values of the sublists in i align with values at index 0 in the sublists of s , but they are not same order.如您所见, i中的子列表的值与s的子列表中索引 0 处的值对齐,但它们的顺序不同。 Now I want to order the values in s based on the values in i like this:现在我想根据i中的值对s中的值进行排序,如下所示:

s_new = [[[921, 640],[4821, 40], [4007, 49]],
        [[1943, 393],[1270, 20], [4821, 183]],
        [[4821, 83],[1300, 95], [857, 641]]]

I tried this code based other questions with similar answers:我尝试了基于其他问题的代码,并给出了类似的答案:

s_new = [(sorted(x, key=lambda item: i.index(item[0]))) for x in s]

But I get the error:但我得到了错误:

ValueError: 921 is not in list

What am I doing wrong and why am I getting this error?我做错了什么,为什么会出现此错误?

I asked this question yesterday but it got marked as duplicate.我昨天问了这个问题,但它被标记为重复。 However the linked questions and answers couldn't solve my problem.但是,链接的问题和答案无法解决我的问题。

You are missing a nested level, you can do this:您缺少嵌套级别,您可以这样做:

s = [[[921, 640], [4007, 49], [4821, 40]],
     [[1270, 20], [1943, 393], [4821, 183]],
     [[1300, 95], [857, 641], [4821, 83]]]

i = [[921, 4821, 4007], [1943, 1270, 4821], [4821, 1300, 857]]

s_new = [(sorted(x, key=lambda item: i[j].index(item[0]))) for j, x in enumerate(s)]

for x in s_new:
    print(x) 

Output Output

[[921, 640], [4821, 40], [4007, 49]]
[[1943, 393], [1270, 20], [4821, 183]]
[[4821, 83], [1300, 95], [857, 641]]

Also note that the i from your example is 4821 instead of 4281 .另请注意,您示例中的i4821而不是4281 As an alternative you could iterate in parallel over the two list using zip:作为替代方案,您可以使用 zip 在两个列表上并行迭代:

s_new = [sorted(si, key=lambda x: ij.index(x[0])) for si, ij in zip(s, i)]

The two approaches above are O(n*n) due to the index call, for longer list is better to use a lookup dictionary, for example:由于索引调用,上述两种方法是O(n*n) ,对于更长的列表最好使用查找字典,例如:

def sort(ls, order):
    priority = {k: p for p, k in enumerate(order)}
    return sorted(ls, key=lambda x: priority[x[0]])


s_new = [sort(si, ij) for si, ij in zip(s, i)]

Using a dictionary makes it O(n log n) that is the cost of a standard sorting algorithm.使用字典使其成为标准排序算法的成本O(n log n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM