tstseby
tstseby

Reputation: 1319

Sort Two Lists in Python with respect to one list

I have two lists, one list is for images, another is for arrays.

l1 = [img1, img2, img3]

l2 = [[1, 2, 3, 4], [3, 5, 5], [1, 4, 5, 9, 8, 8]]

I want to sort list2 by length, which I can do as:

l2 = sorted(l2, key=lambda e: len(e[0]), reverse=True)

Now, the order of elements in l2 has changed,

I want to preserve the images belonging to these lists,

i.e. l1 also must be organized so that img1 -> corresponds to [1, 2, 3, 4]

How can do this? thanks for the help.

Upvotes: 0

Views: 58

Answers (1)

Austin
Austin

Reputation: 26057

Use zip() with sorted:

l1 = ['img1', 'img2', 'img3']

l2 = [[1, 2, 3, 4], [3, 5, 5], [1, 4, 5, 9, 8, 8]]

l1, l2 = zip(*sorted(zip(l1, l2), key=lambda x: len(x[1]), reverse=True))

print(list(l1)) # ['img3', 'img1', 'img2']
print(list(l2)) # [[1, 4, 5, 9, 8, 8], [1, 2, 3, 4], [3, 5, 5]]

Upvotes: 1

Related Questions