Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f50cc9a

Browse files
committed
merge 3.5
2 parents 3f69f02 + 047ada4 commit f50cc9a

1 file changed

Lines changed: 1 addition & 30 deletions

File tree

Doc/faq/programming.rst

Lines changed: 1 addition & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1313,40 +1313,11 @@ I want to do a complicated sort: can you do a Schwartzian Transform in Python?
13131313

13141314
The technique, attributed to Randal Schwartz of the Perl community, sorts the
13151315
elements of a list by a metric which maps each element to its "sort value". In
1316-
Python, just use the ``key`` argument for the ``sort()`` method::
1316+
Python, use the ``key`` argument for the :func:`sort()` function::
13171317

13181318
Isorted = L[:]
13191319
Isorted.sort(key=lambda s: int(s[10:15]))
13201320

1321-
The ``key`` argument is new in Python 2.4, for older versions this kind of
1322-
sorting is quite simple to do with list comprehensions. To sort a list of
1323-
strings by their uppercase values::
1324-
1325-
tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
1326-
tmp1.sort()
1327-
Usorted = [x[1] for x in tmp1]
1328-
1329-
To sort by the integer value of a subfield extending from positions 10-15 in
1330-
each string::
1331-
1332-
tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
1333-
tmp2.sort()
1334-
Isorted = [x[1] for x in tmp2]
1335-
1336-
For versions prior to 3.0, Isorted may also be computed by ::
1337-
1338-
def intfield(s):
1339-
return int(s[10:15])
1340-
1341-
def Icmp(s1, s2):
1342-
return cmp(intfield(s1), intfield(s2))
1343-
1344-
Isorted = L[:]
1345-
Isorted.sort(Icmp)
1346-
1347-
but since this method calls ``intfield()`` many times for each element of L, it
1348-
is slower than the Schwartzian Transform.
1349-
13501321

13511322
How can I sort one list by values from another list?
13521323
----------------------------------------------------

0 commit comments

Comments
 (0)