8000 comment about reverse · adrianhust/python_reference@6e74774 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6e74774

Browse files
committed
comment about reverse
1 parent b87aec3 commit 6e74774

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed
Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# Sebastian Raschka 09/02/2014
2-
# Sorting a list of tuples by th 8000 e last elements of the tuple
3-
2+
# Sorting a list of tuples by starting with the last element of the tuple (=reversed tuple)
43

54
# Here, we make use of the "key" parameter of the in-built "sorted()" function
65
# (also available for the ".sort()" method), which let's us define a function
@@ -9,11 +8,27 @@
98
# from every tuple.
109

1110

12-
13-
a_list = [(1,3,'c'), (2,3,'a'), (1,2,'b')]
11+
a_list = [(1,3,'c'), (2,3,'a'), (3,2,'b'), (2,2,'b')]
1412

1513
sorted_list = sorted(a_list, key=lambda e: e[::-1])
1614

1715
print(sorted_list)
1816

19-
# prints [(2, 3, 'a'), (1, 2, 'b'), (1, 3, 'c')]
17+
# prints [(2, 3, 'a'), (2, 2, 'b'), (3, 2, 'b'), (1, 3, 'c')]
18+
19+
20+
21+
# If we are only interesting in sorting the list by the last element
22+
# of the tuple and don't care about a "tie" situation, we can also use
23+
# the index of the tuple item directly instead of reversing the tuple
24+
# for efficiency.
25+
26+
27+
28+
a_list = [(1,3,'c'), (2,3,'a'), (3,2,'b'), (2,2,'b')]
29+
30+
sorted_list = sorted(a_list, key=lambda e: e[-1])
31+
32+
print(sorted_list)
33+
34+
# prints [(2, 3, 'a'), (3, 2, 'b'), (2, 2, 'b'), (1, 3, 'c')]

0 commit comments

Comments
 (0)
0