[Python] Sorting the list by several attributes in Python

Discussão em 'Python' iniciado por Stack, Março 23, 2025.

  1. Stack

    Stack Membro Participativo

    Given a list of lts2 = [[10, 0, 0, 'H', 9, 11],[8, 2, 2, 'B', 7, 5],[1, 6, 6, 'A', 2, 4],[11, 6, 6, 'F', 10, 5],[13, 8, 8, 'G', 14, 16],[14, 8, 8, 'U', 13, 15],[15, 8, 8, 'J', 14, 16],[3, 10, 10, 'P', 2, 4],[4, 10, 10, 'C', 3, 1],[7, 10, 10, 'T', 6, 8],[5, 12, 12, 'I', 12, 8],[12, 12, 12, 'W', 11, 3],[2, 16, 16, 'D', 1, 9],[6, 18, 18, 'V', 5, 7],[16, 18, 18, 'Q', 15, 13],[9, 24, 24, 'E', 10, 12]]. I need to sort so that the lists in the neighborhood do not have the same values i.e. s[4:] should have no common values with s[i+1][:1] and s[i-1][:1]. But every fourth value should be compared not with the fifth, but with the first. The comparison should go like this 15->14->13->12->15 Next 11->10->9->8->11. The output is a list of lists. The code below is what I was able to do. But this is sorting in order.

    a = 1
    b = 0
    while(a <= len(lst2)):
    if(len(lst2[len(lst2)-a-1-b][4:]) == len(set(lst2[len(lst2)-a-1-b][4:])-set(lst2[len(lst2)-a][:1]))):
    if(b > 0):
    lst2[len(lst2)-a-1-b],lst2[len(lst2)-a-1] = lst2[len(lst2)-a-1],lst2[len(lst2)-a-1-b]
    a = a + 1
    b = 0
    else:
    b = b + 1

    Continue reading...

Compartilhe esta Página