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

Skip to content

Commit de2836d

Browse files
committed
Cleanup: use sorted() whereever possible.
1 parent 45e4a46 commit de2836d

31 files changed

+117
-238
lines changed

doc/sphinxext/math_symbol_table.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,14 +106,10 @@ def get_n(n, l):
106106

107107
lines = []
108108
for category, columns, syms in symbols:
109-
syms = syms.split()
110-
syms.sort()
109+
syms = sorted(syms.split())
111110
lines.append("**%s**" % category)
112111
lines.append('')
113-
max_width = 0
114-
for sym in syms:
115-
max_width = max(max_width, len(sym))
116-
max_width = max_width * 2 + 16
112+
max_width = max(map(len, syms)) * 2 + 16
117113
header = " " + (('=' * max_width) + ' ') * columns
118114
format = '%%%ds' % max_width
119115
for chunk in get_n(20, get_n(columns, syms)):

doc/utils/pylab_names.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,9 @@
44
"""
55
from pylab import *
66
d = locals()
7-
keys = d.keys()
8-
keys.sort()
97

108
modd = dict()
11-
for k in keys:
9+
for k in sorted(d):
1210
o = d[k]
1311
if not callable(o):
1412
continue
@@ -37,10 +35,8 @@
3735
mod, k, doc = mod.strip(), k.strip(), doc.strip()[:80]
3836
modd.setdefault(mod, []).append((k, doc))
3937

40-
mods = modd.keys()
41-
mods.sort()
42-
for mod in mods:
43-
border = '*'*len(mod)
38+
for mod in sorted(modd):
39+
border = '*' * len(mod)
4440
print(mod)
4541
print(border)
4642

examples/pylab_examples/font_table_ttf.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@
3232
'fonts', 'ttf', 'DejaVuSans.ttf')
3333

3434
font = FT2Font(fontname)
35-
codes = list(font.get_charmap().items())
36-
codes.sort()
35+
codes = sorted(font.get_charmap().items())
3736

3837
# a 16,16 array of character strings
3938
chars = [['' for c in range(16)] for r in range(16)]

examples/style_sheets/style_sheets_reference.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,8 @@ def plot_figure(style_label=""):
135135
# Setup a list of all available styles, in alphabetical order but
136136
# the `default` and `classic` ones, which will be forced resp. in
137137
# first and second position.
138-
style_list = list(plt.style.available) # *new* list: avoids side effects.
138+
style_list = sorted(plt.style.available) # *new* list: avoids side effects.
139139
style_list.remove('classic') # `classic` is in the list: first remove it.
140-
style_list.sort()
141140
style_list.insert(0, u'default')
142141
style_list.insert(1, u'classic')
143142

lib/matplotlib/__init__.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -968,9 +968,7 @@ def keys(self):
968968
"""
969969
Return sorted list of keys.
970970
"""
971-
k = list(dict.keys(self))
972-
k.sort()
973-
return k
971+
return sorted(self)
974972

975973
def values(self):
976974
"""

lib/matplotlib/axes/_base.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2376,36 +2376,35 @@ def draw(self, renderer=None, inframe=False):
23762376
artists.remove(self._left_title)
23772377
artists.remove(self._right_title)
23782378

2379-
if self.figure.canvas.is_saving():
2380-
dsu = [(a.zorder, a) for a in artists]
2381-
else:
2382-
dsu = [(a.zorder, a) for a in artists
2383-
if (not a.get_animated() or a in self.images)]
2384-
2385-
dsu.sort(key=itemgetter(0))
2379+
if not self.figure.canvas.is_saving():
2380+
artists = [a for a in artists
2381+
if not a.get_animated() or a in self.images]
2382+
artists = sorted(artists, key=lambda artist: artist.get_zorder())
23862383

23872384
# rasterize artists with negative zorder
23882385
# if the minimum zorder is negative, start rasterization
23892386
rasterization_zorder = self._rasterization_zorder
23902387
if (rasterization_zorder is not None and
2391-
len(dsu) > 0 and dsu[0][0] < rasterization_zorder):
2388+
artists and artists[0].get_zorder() < rasterization_zorder):
23922389
renderer.start_rasterizing()
2393-
dsu_rasterized = [l for l in dsu if l[0] < rasterization_zorder]
2394-
dsu = [l for l in dsu if l[0] >= rasterization_zorder]
2390+
artists_rasterized = [a for a in artists
2391+
if a.get_zorder() < rasterization_zorder]
2392+
artists = [a for a in artists
2393+
if a.get_zorder() >= rasterization_zorder]
23952394
else:
2396-
dsu_rasterized = []
2395+
artists_rasterized = []
23972396

23982397
# the patch draws the background rectangle -- the frame below
23992398
# will draw the edges
24002399
if self.axison and self._frameon:
24012400
self.patch.draw(renderer)
24022401

2403-
if dsu_rasterized:
2404-
for zorder, a in dsu_rasterized:
2402+
if artists_rasterized:
2403+
for a in artists_rasterized:
24052404
a.draw(renderer)
24062405
renderer.stop_rasterizing()
24072406

2408-
mimage._draw_list_compositing_images(renderer, self, dsu)
2407+
mimage._draw_list_compositing_images(renderer, self, artists)
24092408

24102409
renderer.close_group('axes')
24112410
self._cachedRenderer = renderer

lib/matplotlib/axis.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -951,16 +951,12 @@ def _update_ticks(self, renderer):
951951
"""
952952

953953
interval = self.get_view_interval()
954-
tick_tups = [t for t in self.iter_ticks()]
954+
tick_tups = list(self.iter_ticks())
955955
if self._smart_bounds:
956956
# handle inverted limits
957-
view_low, view_high = min(*interval), max(*interval)
958-
data_low, data_high = self.get_data_interval()
959-
if data_low > data_high:
960-
data_low, data_high = data_high, data_low
961-
locs = [ti[1] for ti in tick_tups]
962-
locs.sort()
963-
locs = np.array(locs)
957+
view_low, view_high = min(interval), max(interval)
958+
data_low, data_high = sorted(self.get_data_interval())
959+
locs = np.sort(ti[1] for ti in tick_tups)
964960
if len(locs):
965961
if data_low <= view_low:
966962
# data extends beyond view, take view as limit

lib/matplotlib/backend_bases.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1469,15 +1469,12 @@ def __init__(self, name, canvas, x, y, guiEvent=None):
14691469
else:
14701470
axes_list = [self.canvas.mouse_grabber]
14711471

1472-
if len(axes_list) == 0: # None found
1472+
if axes_list: # Use highest zorder.
1473+
self.inaxes = max(axes_list, key=lambda x: x.zorder)
1474+
else: # None found.
14731475
self.inaxes = None
14741476
self._update_enter_leave()
14751477
return
1476-
elif (len(axes_list) > 1): # Overlap, get the highest zorder
1477-
axes_list.sort(key=lambda x: x.zorder)
1478-
self.inaxes = axes_list[-1] # Use the highest zorder
1479-
else: # Just found one hit
1480-
self.inaxes = axes_list[0]
14811478

14821479
try:
14831480
trans = self.inaxes.transData.inverted()
@@ -1751,8 +1748,7 @@ def onRemove(self, ev):
17511748
canvas.mpl_connect('mouse_press_event',canvas.onRemove)
17521749
"""
17531750
# Find the top artist under the cursor
1754-
under = self.figure.hitlist(ev)
1755-
under.sort(key=lambda x: x.zorder)
1751+
under = sorted(self.figure.hitlist(ev), key=lambda x: x.zorder)
17561752
h = None
17571753
if under:
17581754
h = under[-1]

lib/matplotlib/backends/backend_gdk.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,8 @@ def fn_name(): return sys._getframe(1).f_code.co_name
3636
_debug = False
3737

3838
# Image formats that this backend supports - for FileChooser and print_figure()
39-
IMAGE_FORMAT = ['eps', 'jpg', 'png', 'ps', 'svg'] + ['bmp'] # , 'raw', 'rgb']
40-
IMAGE_FORMAT.sort()
41-
IMAGE_FORMAT_DEFAULT = 'png'
39+
IMAGE_FORMAT = sorted(['eps', 'jpg', 'png', 'ps', 'svg'] + ['bmp']) # , 'raw', 'rgb']
40+
IMAGE_FORMAT_DEFAULT = 'png'
4241

4342

4443
class RendererGDK(RendererBase):

lib/matplotlib/backends/backend_gtk.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -829,33 +829,32 @@ def __init__ (self,
829829
filetypes = [],
830830
default_filetype = None
831831
):
832-
super(FileChooserDialog, self).__init__ (title, parent, action,
833-
buttons)
832+
super(FileChooserDialog, self).__init__(title, parent, action, buttons)
834833
super(FileChooserDialog, self).set_do_overwrite_confirmation(True)
835-
self.set_default_response (gtk.RESPONSE_OK)
834+
self.set_default_response(gtk.RESPONSE_OK)
836835

837-
if not path: path = os.getcwd() + os.sep
836+
if not path:
837+
path = os.getcwd() + os.sep
838838

839839
# create an extra widget to list supported image formats
840840
self.set_current_folder (path)
841841
self.set_current_name ('image.' + default_filetype)
842842

843-
hbox = gtk.HBox (spacing=10)
844-
hbox.pack_start (gtk.Label ("File Format:"), expand=False)
843+
hbox = gtk.HBox(spacing=10)
844+
hbox.pack_start(gtk.Label ("File Format:"), expand=False)
845845

846846
liststore = gtk.ListStore(gobject.TYPE_STRING)
847847
cbox = gtk.ComboBox(liststore)
848848
cell = gtk.CellRendererText()
849849
cbox.pack_start(cell, True)
850850
cbox.add_attribute(cell, 'text', 0)
851-
hbox.pack_start (cbox)
851+
hbox.pack_start(cbox)
852852

853853
self.filetypes = filetypes
854-
self.sorted_filetypes = list(six.iteritems(filetypes))
855-
self.sorted_filetypes.sort()
854+
self.sorted_filetypes = sorted(six.iteritems(filetypes))
856855
default = 0
857856
for i, (ext, name) in enumerate(self.sorted_filetypes):
858-
cbox.append_text ("%s (*.%s)" % (name, ext))
857+
cbox.append_text("%s (*.%s)" % (name, ext))
859858
if ext == default_filetype:
860859
default = i
861860
cbox.set_active(default)
@@ -874,8 +873,8 @@ def cb_cbox_changed (cbox, data=None):
874873
elif ext == '':
875874
filename = filename.rstrip('.') + '.' + new_ext
876875

877-
self.set_current_name (filename)
878-
cbox.connect ("changed", cb_cbox_changed)
876+
self.set_current_name(filename)
877+
cbox.connect("changed", cb_cbox_changed)
879878

880879
hbox.show_all()
881880
self.set_extra_widget(hbox)

lib/matplotlib/backends/backend_gtk3.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -696,8 +696,7 @@ def __init__ (self,
696696
hbox.pack_start(cbox, False, False, 0)
697697

698698
self.filetypes = filetypes
699-
self.sorted_filetypes = list(six.iteritems(filetypes))
700-
self.sorted_filetypes.sort()
699+
self.sorted_filetypes = sorted(six.iteritems(filetypes))
701700
default = 0
702701
for i, (ext, name) in enumerate(self.sorted_filetypes):
703702
liststore.append(["%s (*.%s)" % (name, ext)])

lib/matplotlib/backends/backend_qt5.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -711,8 +711,7 @@ def configure_subplots(self):
711711

712712
def save_figure(self, *args):
713713
filetypes = self.canvas.get_supported_filetypes_grouped()
714-
sorted_filetypes = list(six.iteritems(filetypes))
715-
sorted_filetypes.sort()
714+
sorted_filetypes = sorted(six.iteritems(filetypes))
716715
default_filetype = self.canvas.get_default_filetype()
717716

718717
startpath = matplotlib.rcParams.get('savefig.directory', '')

lib/matplotlib/backends/backend_svg.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,7 @@ def start(self, tag, attrib={}, **extra):
145145
if attrib or extra:
146146
attrib = attrib.copy()
147147
attrib.update(extra)
148-
attrib = list(six.iteritems(attrib))
149-
attrib.sort()
148+
attrib = sorted(six.iteritems(attrib))
150149
for k, v in attrib:
151150
if not v == '':
152151
k = escape_cdata(k)
@@ -248,8 +247,7 @@ def generate_transform(transform_list=[]):
248247
def generate_css(attrib={}):
249248
if attrib:
250249
output = io.StringIO()
251-
attrib = list(six.iteritems(attrib))
252-
attrib.sort()
250+
attrib = sorted(six.iteritems(attrib))
253251
for k, v in attrib:
254252
k = escape_attrib(k)
255253
v = escape_attrib(v)

lib/matplotlib/backends/backend_tkagg.py

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -810,15 +810,10 @@ def save_figure(self, *args):
810810

811811
# Tk doesn't provide a way to choose a default filetype,
812812
# so we just have to put it first
813-
default_filetype_name = filetypes[default_filetype]
814-
del filetypes[default_filetype]
815-
816-
sorted_filetypes = list(six.iteritems(filetypes))
817-
sorted_filetypes.sort()
818-
sorted_filetypes.insert(0, (default_filetype, default_filetype_name))
819-
820-
tk_filetypes = [
821-
(name, '*.%s' % ext) for (ext, name) in sorted_filetypes]
813+
default_filetype_name = filetypes.pop(default_filetype)
814+
sorted_filetypes = ([(default_filetype, default_filetype_name)]
815+
+ sorted(six.iteritems(filetypes)))
816+
tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes]
822817

823818
# adding a default extension seems to break the
824819
# asksaveasfilename dialog when you choose various save types
@@ -1050,15 +1045,10 @@ def trigger(self, *args):
10501045

10511046
# Tk doesn't provide a way to choose a default filetype,
10521047
# so we just have to put it first
1053-
default_filetype_name = filetypes[default_filetype]
1054-
del filetypes[default_filetype]
1055-
1056-
sorted_filetypes = list(six.iteritems(filetypes))
1057-
sorted_filetypes.sort()
1058-
sorted_filetypes.insert(0, (default_filetype, default_filetype_name))
1059-
1060-
tk_filetypes = [
1061-
(name, '*.%s' % ext) for (ext, name) in sorted_filetypes]
1048+
default_filetype_name = filetypes.pop(default_filetype)
1049+
sorted_filetypes = ([(default_filetype, default_filetype_name)]
1050+
+ sorted(six.iteritems(filetypes)))
1051+
tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes]
10621052

10631053
# adding a default extension seems to break the
10641054
# asksaveasfilename dialog when you choose various save types

lib/matplotlib/cbook.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -884,8 +884,7 @@ def byItem(self, data, itemindex=None, inplace=1):
884884
data.sort()
885885
result = data
886886
else:
887-
result = data[:]
888-
result.sort()
887+
result = sorted(data)
889888
return result
890889
else:
891890
aux = [(data[i][itemindex], i) for i in range(len(data))]

lib/matplotlib/colors.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -370,10 +370,9 @@ def makeMappingArray(N, data, gamma=1.0):
370370

371371
if x[0] != 0. or x[-1] != 1.0:
372372
raise ValueError(
373-
"data mapping points must start with x=0. and end with x=1")
374-
if np.sometrue(np.sort(x) - x):
375-
raise ValueError(
376-
"data mapping points must have x in increasing order")
373+
"data mapping points must start with x=0 and end with x=1")
374+
if (np.diff(x) < 0).any():
375+
raise ValueError("data mapping points must have x in increasing order")
377376
# begin generation of lookup table
378377
x = x * (N - 1)
379378
lut = np.zeros((N,), float)

0 commit comments

Comments
 (0)