Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Cleanup: sorted, dict iteration, array.{ndim,size}, ...#7549

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
QuLogic merged 9 commits intomatplotlib:masterfromanntzer:cleanup-sorted
Dec 22, 2016
Merged
Show file tree
Hide file tree
Changes from1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
NextNext commit
Cleanup: usesorted() whereever possible.
  • Loading branch information
@anntzer
anntzer committedDec 21, 2016
commit70909c4d9dcaa287e57b90cb24278e5f016992ce
8 changes: 2 additions & 6 deletionsdoc/sphinxext/math_symbol_table.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -106,14 +106,10 @@ def get_n(n, l):

lines = []
for category, columns, syms in symbols:
syms = syms.split()
syms.sort()
syms = sorted(syms.split())
lines.append("**%s**" % category)
lines.append('')
max_width = 0
for sym in syms:
max_width = max(max_width, len(sym))
max_width = max_width * 2 + 16
max_width = max(map(len, syms)) * 2 + 16
header = " " + (('=' * max_width) + ' ') * columns
format = '%%%ds' % max_width
for chunk in get_n(20, get_n(columns, syms)):
Expand Down
10 changes: 3 additions & 7 deletionsdoc/utils/pylab_names.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,9 @@
"""
from pylab import *
d = locals()
keys = d.keys()
keys.sort()

modd = dict()
for k inkeys:
for k insorted(d):
o = d[k]
if not callable(o):
continue
Expand DownExpand Up@@ -37,10 +35,8 @@
mod, k, doc = mod.strip(), k.strip(), doc.strip()[:80]
modd.setdefault(mod, []).append((k, doc))

mods = modd.keys()
mods.sort()
for mod in mods:
border = '*'*len(mod)
for mod in sorted(modd):
border = '*' * len(mod)
print(mod)
print(border)

Expand Down
3 changes: 1 addition & 2 deletionsexamples/pylab_examples/font_table_ttf.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,8 +32,7 @@
'fonts', 'ttf', 'DejaVuSans.ttf')

font = FT2Font(fontname)
codes = list(font.get_charmap().items())
codes.sort()
codes = sorted(font.get_charmap().items())

# a 16,16 array of character strings
chars = [['' for c in range(16)] for r in range(16)]
Expand Down
7 changes: 2 additions & 5 deletionsexamples/style_sheets/style_sheets_reference.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,11 +135,8 @@ def plot_figure(style_label=""):
# Setup a list of all available styles, in alphabetical order but
# the `default` and `classic` ones, which will be forced resp. in
# first and second position.
style_list = list(plt.style.available) # *new* list: avoids side effects.
style_list.remove('classic') # `classic` is in the list: first remove it.
style_list.sort()
style_list.insert(0, u'default')
style_list.insert(1, u'classic')
style_list = ['default', 'classic'] + sorted(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

👍

style for style in plt.style.available if style != 'classic')

# Plot a demonstration figure for every available style sheet.
for style_label in style_list:
Expand Down
4 changes: 1 addition & 3 deletionslib/matplotlib/__init__.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -968,9 +968,7 @@ def keys(self):
"""
Return sorted list of keys.
"""
k = list(dict.keys(self))
k.sort()
return k
return sorted(self)

def values(self):
"""
Expand Down
27 changes: 13 additions & 14 deletionslib/matplotlib/axes/_base.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2365,36 +2365,35 @@ def draw(self, renderer=None, inframe=False):
artists.remove(self._left_title)
artists.remove(self._right_title)

if self.figure.canvas.is_saving():
dsu = [(a.zorder, a) for a in artists]
else:
dsu = [(a.zorder, a) for a in artists
if (not a.get_animated() or a in self.images)]

dsu.sort(key=itemgetter(0))
if not self.figure.canvas.is_saving():
artists = [a for a in artists
if not a.get_animated() or a in self.images]
artists = sorted(artists, key=lambda artist: artist.get_zorder())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Is notattrgetter faster thanlambda?

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I doubt it matters but sure.


# rasterize artists with negative zorder
# if the minimum zorder is negative, start rasterization
rasterization_zorder = self._rasterization_zorder
if (rasterization_zorder is not None and
len(dsu) > 0anddsu[0][0] < rasterization_zorder):
artistsandartists[0].get_zorder() < rasterization_zorder):
renderer.start_rasterizing()
dsu_rasterized = [l for l in dsu if l[0] < rasterization_zorder]
dsu = [l for l in dsu if l[0] >= rasterization_zorder]
artists_rasterized = [a for a in artists
if a.get_zorder() < rasterization_zorder]
artists = [a for a in artists
if a.get_zorder() >= rasterization_zorder]
else:
dsu_rasterized = []
artists_rasterized = []

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

ifdsu_rasterized:
forzorder,a indsu_rasterized:
ifartists_rasterized:
for a inartists_rasterized:
a.draw(renderer)
renderer.stop_rasterizing()

mimage._draw_list_compositing_images(renderer, self,dsu)
mimage._draw_list_compositing_images(renderer, self,artists)

renderer.close_group('axes')
self._cachedRenderer = renderer
Expand Down
62 changes: 27 additions & 35 deletionslib/matplotlib/axis.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -951,45 +951,37 @@ def _update_ticks(self, renderer):
"""

interval = self.get_view_interval()
tick_tups =[t for t inself.iter_ticks()]
tick_tups =list(self.iter_ticks())
if self._smart_bounds:
# handle inverted limits
view_low, view_high = min(*interval), max(*interval)
data_low, data_high = self.get_data_interval()
if data_low > data_high:
data_low, data_high = data_high, data_low
locs = [ti[1] for ti in tick_tups]
locs.sort()
locs = np.array(locs)
if len(locs):
if data_low <= view_low:
# data extends beyond view, take view as limit
ilow = view_low
view_low, view_high = min(interval), max(interval)
data_low, data_high = sorted(self.get_data_interval())
locs = np.sort([ti[1] for ti in tick_tups])
if data_low <= view_low:
# data extends beyond view, take view as limit
ilow = view_low
else:
# data stops within view, take best tick
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I understand this condition is probably not necessary, but I guess it could also beanded onto line 955?

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

In fact it's probably needed, otherwise we may end up trying to get the first or last item of an empty array...

good_locs = locs[locs <= data_low]
if len(good_locs) > 0:
# last tick prior or equal to first data point
ilow = good_locs[-1]
else:
# data stops within view, take best tick
cond = locs <= data_low
good_locs = locs[cond]
if len(good_locs) > 0:
# last tick prior or equal to first data point
ilow = good_locs[-1]
else:
# No ticks (why not?), take first tick
ilow = locs[0]
if data_high >= view_high:
# data extends beyond view, take view as limit
ihigh = view_high
# No ticks (why not?), take first tick
ilow = locs[0]
if data_high >= view_high:
# data extends beyond view, take view as limit
ihigh = view_high
else:
# data stops within view, take best tick
good_locs = locs[locs >= data_high]
if len(good_locs) > 0:
# first tick after or equal to last data point
ihigh = good_locs[0]
else:
# data stops within view, take best tick
cond = locs >= data_high
good_locs = locs[cond]
if len(good_locs) > 0:
# first tick after or equal to last data point
ihigh = good_locs[0]
else:
# No ticks (why not?), take last tick
ihigh = locs[-1]
tick_tups = [ti for ti in tick_tups
if (ti[1] >= ilow) and (ti[1] <= ihigh)]
# No ticks (why not?), take last tick
ihigh = locs[-1]
tick_tups = [ti for ti in tick_tups if ilow <= ti[1] <= ihigh]

# so that we don't lose ticks on the end, expand out the interval ever
# so slightly. The "ever so slightly" is defined to be the width of a
Expand Down
12 changes: 4 additions & 8 deletionslib/matplotlib/backend_bases.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1469,15 +1469,12 @@ def __init__(self, name, canvas, x, y, guiEvent=None):
else:
axes_list = [self.canvas.mouse_grabber]

if len(axes_list) == 0: # None found
if axes_list: # Use highest zorder.
self.inaxes = max(axes_list, key=lambda x: x.zorder)
else: # None found.
self.inaxes = None
self._update_enter_leave()
return
elif (len(axes_list) > 1): # Overlap, get the highest zorder
axes_list.sort(key=lambda x: x.zorder)
self.inaxes = axes_list[-1] # Use the highest zorder
else: # Just found one hit
self.inaxes = axes_list[0]

try:
trans = self.inaxes.transData.inverted()
Expand DownExpand Up@@ -1751,8 +1748,7 @@ def onRemove(self, ev):
canvas.mpl_connect('mouse_press_event',canvas.onRemove)
"""
# Find the top artist under the cursor
under = self.figure.hitlist(ev)
under.sort(key=lambda x: x.zorder)
under = sorted(self.figure.hitlist(ev), key=lambda x: x.zorder)
h = None
if under:
h = under[-1]
Expand Down
5 changes: 2 additions & 3 deletionslib/matplotlib/backends/backend_gdk.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,9 +36,8 @@ def fn_name(): return sys._getframe(1).f_code.co_name
_debug = False

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Just put'bmp' at the front?

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Sure, but I'll keep thesorted which makes the intent clear and should be cheap.

IMAGE_FORMAT_DEFAULT = 'png'


class RendererGDK(RendererBase):
Expand Down
23 changes: 11 additions & 12 deletionslib/matplotlib/backends/backend_gtk.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -829,33 +829,32 @@ def __init__ (self,
filetypes = [],
default_filetype = None
):
super(FileChooserDialog, self).__init__ (title, parent, action,
buttons)
super(FileChooserDialog, self).__init__(title, parent, action, buttons)
super(FileChooserDialog, self).set_do_overwrite_confirmation(True)
self.set_default_response(gtk.RESPONSE_OK)
self.set_default_response(gtk.RESPONSE_OK)

if not path: path = os.getcwd() + os.sep
if not path:
path = os.getcwd() + os.sep

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

hbox = gtk.HBox(spacing=10)
hbox.pack_start(gtk.Label ("File Format:"), expand=False)
hbox = gtk.HBox(spacing=10)
hbox.pack_start(gtk.Label ("File Format:"), expand=False)

liststore = gtk.ListStore(gobject.TYPE_STRING)
cbox = gtk.ComboBox(liststore)
cell = gtk.CellRendererText()
cbox.pack_start(cell, True)
cbox.add_attribute(cell, 'text', 0)
hbox.pack_start(cbox)
hbox.pack_start(cbox)

self.filetypes = filetypes
self.sorted_filetypes = list(six.iteritems(filetypes))
self.sorted_filetypes.sort()
self.sorted_filetypes = sorted(six.iteritems(filetypes))
default = 0
for i, (ext, name) in enumerate(self.sorted_filetypes):
cbox.append_text("%s (*.%s)" % (name, ext))
cbox.append_text("%s (*.%s)" % (name, ext))
if ext == default_filetype:
default = i
cbox.set_active(default)
Expand All@@ -874,8 +873,8 @@ def cb_cbox_changed (cbox, data=None):
elif ext == '':
filename = filename.rstrip('.') + '.' + new_ext

self.set_current_name(filename)
cbox.connect("changed", cb_cbox_changed)
self.set_current_name(filename)
cbox.connect("changed", cb_cbox_changed)

hbox.show_all()
self.set_extra_widget(hbox)
Expand Down
3 changes: 1 addition & 2 deletionslib/matplotlib/backends/backend_gtk3.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -695,8 +695,7 @@ def __init__ (self,
hbox.pack_start(cbox, False, False, 0)

self.filetypes = filetypes
self.sorted_filetypes = list(six.iteritems(filetypes))
self.sorted_filetypes.sort()
self.sorted_filetypes = sorted(six.iteritems(filetypes))
default = 0
for i, (ext, name) in enumerate(self.sorted_filetypes):
liststore.append(["%s (*.%s)" % (name, ext)])
Expand Down
3 changes: 1 addition & 2 deletionslib/matplotlib/backends/backend_qt5.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -719,8 +719,7 @@ def configure_subplots(self):

def save_figure(self, *args):
filetypes = self.canvas.get_supported_filetypes_grouped()
sorted_filetypes = list(six.iteritems(filetypes))
sorted_filetypes.sort()
sorted_filetypes = sorted(six.iteritems(filetypes))
default_filetype = self.canvas.get_default_filetype()

startpath = matplotlib.rcParams.get('savefig.directory', '')
Expand Down
6 changes: 2 additions & 4 deletionslib/matplotlib/backends/backend_svg.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -145,8 +145,7 @@ def start(self, tag, attrib={}, **extra):
if attrib or extra:
attrib = attrib.copy()
attrib.update(extra)
attrib = list(six.iteritems(attrib))
attrib.sort()
attrib = sorted(six.iteritems(attrib))
for k, v in attrib:
if not v == '':
k = escape_cdata(k)
Expand DownExpand Up@@ -248,8 +247,7 @@ def generate_transform(transform_list=[]):
def generate_css(attrib={}):
if attrib:
output = io.StringIO()
attrib = list(six.iteritems(attrib))
attrib.sort()
attrib = sorted(six.iteritems(attrib))
for k, v in attrib:
k = escape_attrib(k)
v = escape_attrib(v)
Expand Down
26 changes: 8 additions & 18 deletionslib/matplotlib/backends/backend_tkagg.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -807,15 +807,10 @@ def save_figure(self, *args):

# Tk doesn't provide a way to choose a default filetype,
# so we just have to put it first
default_filetype_name = filetypes[default_filetype]
del filetypes[default_filetype]

sorted_filetypes = list(six.iteritems(filetypes))
sorted_filetypes.sort()
sorted_filetypes.insert(0, (default_filetype, default_filetype_name))

tk_filetypes = [
(name, '*.%s' % ext) for (ext, name) in sorted_filetypes]
default_filetype_name = filetypes.pop(default_filetype)
sorted_filetypes = ([(default_filetype, default_filetype_name)]
+ sorted(six.iteritems(filetypes)))
tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes]

# adding a default extension seems to break the
# asksaveasfilename dialog when you choose various save types
Expand DownExpand Up@@ -1047,15 +1042,10 @@ def trigger(self, *args):

# Tk doesn't provide a way to choose a default filetype,
# so we just have to put it first
default_filetype_name = filetypes[default_filetype]
del filetypes[default_filetype]

sorted_filetypes = list(six.iteritems(filetypes))
sorted_filetypes.sort()
sorted_filetypes.insert(0, (default_filetype, default_filetype_name))

tk_filetypes = [
(name, '*.%s' % ext) for (ext, name) in sorted_filetypes]
default_filetype_name = filetypes.pop(default_filetype)
sorted_filetypes = ([(default_filetype, default_filetype_name)]
+ sorted(six.iteritems(filetypes)))
tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes]

# adding a default extension seems to break the
# asksaveasfilename dialog when you choose various save types
Expand Down
3 changes: 1 addition & 2 deletionslib/matplotlib/cbook.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -903,8 +903,7 @@ def byItem(self, data, itemindex=None, inplace=1):
data.sort()
result = data
else:
result = data[:]
result.sort()
result = sorted(data)
return result
else:
aux = [(data[i][itemindex], i) for i in range(len(data))]
Expand Down
7 changes: 3 additions & 4 deletionslib/matplotlib/colors.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -372,10 +372,9 @@ def makeMappingArray(N, data, gamma=1.0):

if x[0] != 0. or x[-1] != 1.0:
raise ValueError(
"data mapping points must start with x=0. and end with x=1")
if np.sometrue(np.sort(x) - x):
raise ValueError(
"data mapping points must have x in increasing order")
"data mapping points must start with x=0 and end with x=1")
if (np.diff(x) < 0).any():
raise ValueError("data mapping points must have x in increasing order")
# begin generation of lookup table
x = x * (N - 1)
lut = np.zeros((N,), float)
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp