mirror of
https://github.com/python/cpython.git
synced 2025-12-10 02:50:09 +00:00
bpo-39705 : sorted() tutorial example under looping techniques improved (GH-18999)
This commit is contained in:
parent
65460565df
commit
eefd4e0333
2 changed files with 17 additions and 0 deletions
|
|
@ -613,6 +613,21 @@ direction and then call the :func:`reversed` function. ::
|
|||
To loop over a sequence in sorted order, use the :func:`sorted` function which
|
||||
returns a new sorted list while leaving the source unaltered. ::
|
||||
|
||||
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
|
||||
>>> for i in sorted(basket):
|
||||
... print(i)
|
||||
...
|
||||
apple
|
||||
apple
|
||||
banana
|
||||
orange
|
||||
orange
|
||||
pear
|
||||
|
||||
Using :func:`set` on a sequence eliminates duplicate elements. The use of
|
||||
:func:`sorted` in combination with :func:`set` over a sequence is an idiomatic
|
||||
way to loop over unique elements of the sequence in sorted order. ::
|
||||
|
||||
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
|
||||
>>> for f in sorted(set(basket)):
|
||||
... print(f)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue