-1

I have the following List with a List of tuples:

[[('Armin', 1.0), ('Doris', 0.2240092377397959)], [('Benjamin', 1.0), ('Doris', 0.3090169943749474)], [('Caroline', 1.0), ('Benjamin', 0.2612038749637414)], [('Doris', 1.0), ('Benjamin', 0.3090169943749474)], [('Ernst', 1.0), ('Benjamin', 0.28989794855663564)]]

This is a list of tuples in a list. I would like to sort it by the value of the second tuple in each list. For instance - I would like to have this result of my orderedList:

[[('Benjamin', 1.0), ('Doris', 0.3090169943749474)],[('Doris', 1.0), ('Benjamin', 0.3090169943749474)],[('Ernst', 1.0), ('Benjamin', 0.28989794855663564)],[('Caroline', 1.0), ('Benjamin', 0.2612038749637414)],[('Armin', 1.0), ('Doris', 0.2240092377397959)]]

I was not able to manage it with sorted and lambda.

Could you please tell me how to do it?

Michael
  • 251
  • 1
  • 2
  • 13
  • It is not quite that same as that. He also want the top level list sorted by the sub-sub elements that are not equal to 1.0 – James Nov 12 '17 at 17:00

3 Answers3

1

This should do it:

l = [[('Armin', 1.0), ('Doris', 0.2240092377397959)], [('Benjamin', 1.0), ('Doris', 0.3090169943749474)], [('Caroline', 1.0), ('Benjamin', 0.2612038749637414)], [('Doris', 1.0), ('Benjamin', 0.3090169943749474)], [('Ernst', 1.0), ('Benjamin', 0.28989794855663564)]]

sorted(l, key=lambda x: x[1][1], reverse=True)

Explanation: Passing the key parameter in sorted allows you to sort an object by a key that you specify. In this case, the key we wan to sort on is the second value in the second item of the list. Passing the reverse=True parameter sorts the list in descending order.

0

I think you want this. Sort each sub list by the second value, then sort the top level list by the number of the second value in the sublists.

sorted([sorted(e, key=lambda x: x[-1], reverse=True) for e in x], 
       key=lambda x: x[-1][-1], reverse=True)

# returns:
[[('Benjamin', 1.0), ('Doris', 0.3090169943749474)],
 [('Doris', 1.0), ('Benjamin', 0.3090169943749474)],
 [('Ernst', 1.0), ('Benjamin', 0.28989794855663564)],
 [('Caroline', 1.0), ('Benjamin', 0.2612038749637414)],
 [('Armin', 1.0), ('Doris', 0.2240092377397959)]]
James
  • 32,991
  • 4
  • 47
  • 70
0

You can try this:

s= [[('Armin', 1.0), ('Doris', 0.2240092377397959)], [('Benjamin', 1.0), ('Doris', 0.3090169943749474)], [('Caroline', 1.0), ('Benjamin', 0.2612038749637414)], [('Doris', 1.0), ('Benjamin', 0.3090169943749474)], [('Ernst', 1.0), ('Benjamin', 0.28989794855663564)]]
final_s = [[(a, b) for a, b in zip([c for c, d in i], [d for c, d in i][::-1])][::-1] for i in sorted(s, key=lambda x:x[-1][-1])[::-1]]

Output:

[[('Benjamin', 1.0), ('Doris', 0.3090169943749474)], [('Doris', 1.0), ('Benjamin', 0.3090169943749474)], [('Benjamin', 1.0), ('Ernst', 0.28989794855663564)], [('Benjamin', 1.0), ('Caroline', 0.2612038749637414)], [('Doris', 1.0), ('Armin', 0.2240092377397959)]]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102