summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMatti Picus <matti.picus@gmail.com>2021-09-01 16:51:41 +0300
committerGitHub <noreply@github.com>2021-09-01 16:51:41 +0300
commit68299575d8595d904aff6f28e12d21bf6428a4ba (patch)
treef59f89c4786b8298fe25ef4f082f51366b388bb3
parent0656fc493591be2200b0b0df5e14fb547aa4702f (diff)
parent64f15a94708095bf9d29af5dbfcc4b654a57248a (diff)
downloadnumpy-68299575d8595d904aff6f28e12d21bf6428a4ba.tar.gz
Merge pull request #19781 from mwtoews/foreach-item
MAINT: refactor "for ... in range(len(" statements
-rw-r--r--numpy/core/records.py12
-rw-r--r--numpy/core/tests/test_umath_complex.py16
-rwxr-xr-xnumpy/f2py/f2py2e.py57
-rw-r--r--numpy/lib/index_tricks.py18
-rw-r--r--numpy/lib/polynomial.py23
-rw-r--r--numpy/lib/tests/test_function_base.py5
-rw-r--r--numpy/lib/tests/test_shape_base.py10
-rw-r--r--numpy/lib/utils.py6
8 files changed, 72 insertions, 75 deletions
diff --git a/numpy/core/records.py b/numpy/core/records.py
index b3474ad01..2c20b7d45 100644
--- a/numpy/core/records.py
+++ b/numpy/core/records.py
@@ -664,17 +664,17 @@ def fromarrays(arrayList, dtype=None, shape=None, formats=None,
if nn > 0:
shape = shape[:-nn]
+ _array = recarray(shape, descr)
+
+ # populate the record array (makes a copy)
for k, obj in enumerate(arrayList):
nn = descr[k].ndim
testshape = obj.shape[:obj.ndim - nn]
+ name = _names[k]
if testshape != shape:
- raise ValueError("array-shape mismatch in array %d" % k)
+ raise ValueError(f'array-shape mismatch in array {k} ("{name}")')
- _array = recarray(shape, descr)
-
- # populate the record array (makes a copy)
- for i in range(len(arrayList)):
- _array[_names[i]] = arrayList[i]
+ _array[name] = obj
return _array
diff --git a/numpy/core/tests/test_umath_complex.py b/numpy/core/tests/test_umath_complex.py
index ad09830d4..af5bbe59e 100644
--- a/numpy/core/tests/test_umath_complex.py
+++ b/numpy/core/tests/test_umath_complex.py
@@ -134,8 +134,7 @@ class TestClog:
x = np.array([1+0j, 1+2j])
y_r = np.log(np.abs(x)) + 1j * np.angle(x)
y = np.log(x)
- for i in range(len(x)):
- assert_almost_equal(y[i], y_r[i])
+ assert_almost_equal(y, y_r)
@platform_skip
@pytest.mark.skipif(platform.machine() == "armv5tel", reason="See gh-413.")
@@ -365,8 +364,7 @@ class TestCpow:
x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan])
y_r = x ** 2
y = np.power(x, 2)
- for i in range(len(x)):
- assert_almost_equal(y[i], y_r[i])
+ assert_almost_equal(y, y_r)
def test_scalar(self):
x = np.array([1, 1j, 2, 2.5+.37j, np.inf, np.nan])
@@ -419,8 +417,7 @@ class TestCabs:
x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan])
y_r = np.array([np.sqrt(2.), 2, np.sqrt(5), np.inf, np.nan])
y = np.abs(x)
- for i in range(len(x)):
- assert_almost_equal(y[i], y_r[i])
+ assert_almost_equal(y, y_r)
def test_fabs(self):
# Test that np.abs(x +- 0j) == np.abs(x) (as mandated by C99 for cabs)
@@ -466,9 +463,10 @@ class TestCabs:
return np.abs(complex(a, b))
xa = np.array(x, dtype=complex)
- for i in range(len(xa)):
- ref = g(x[i], y[i])
- check_real_value(f, x[i], y[i], ref)
+ assert len(xa) == len(x) == len(y)
+ for xi, yi in zip(x, y):
+ ref = g(xi, yi)
+ check_real_value(f, xi, yi, ref)
class TestCarg:
def test_simple(self):
diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py
index a14f068f1..f2093d76c 100755
--- a/numpy/f2py/f2py2e.py
+++ b/numpy/f2py/f2py2e.py
@@ -359,33 +359,34 @@ def buildmodules(lst):
cfuncs.buildcfuncs()
outmess('Building modules...\n')
modules, mnames, isusedby = [], [], {}
- for i in range(len(lst)):
- if '__user__' in lst[i]['name']:
- cb_rules.buildcallbacks(lst[i])
+ for item in lst:
+ if '__user__' in item['name']:
+ cb_rules.buildcallbacks(item)
else:
- if 'use' in lst[i]:
- for u in lst[i]['use'].keys():
+ if 'use' in item:
+ for u in item['use'].keys():
if u not in isusedby:
isusedby[u] = []
- isusedby[u].append(lst[i]['name'])
- modules.append(lst[i])
- mnames.append(lst[i]['name'])
+ isusedby[u].append(item['name'])
+ modules.append(item)
+ mnames.append(item['name'])
ret = {}
- for i in range(len(mnames)):
- if mnames[i] in isusedby:
+ for module, name in zip(modules, mnames):
+ if name in isusedby:
outmess('\tSkipping module "%s" which is used by %s.\n' % (
- mnames[i], ','.join(['"%s"' % s for s in isusedby[mnames[i]]])))
+ name, ','.join('"%s"' % s for s in isusedby[name])))
else:
um = []
- if 'use' in modules[i]:
- for u in modules[i]['use'].keys():
+ if 'use' in module:
+ for u in module['use'].keys():
if u in isusedby and u in mnames:
um.append(modules[mnames.index(u)])
else:
outmess(
- '\tModule "%s" uses nonexisting "%s" which will be ignored.\n' % (mnames[i], u))
- ret[mnames[i]] = {}
- dict_append(ret[mnames[i]], rules.buildmodule(modules[i], um))
+ f'\tModule "{name}" uses nonexisting "{u}" '
+ 'which will be ignored.\n')
+ ret[name] = {}
+ dict_append(ret[name], rules.buildmodule(module, um))
return ret
@@ -429,18 +430,20 @@ def run_main(comline_list):
capi_maps.load_f2cmap_file(options['f2cmap_file'])
postlist = callcrackfortran(files, options)
isusedby = {}
- for i in range(len(postlist)):
- if 'use' in postlist[i]:
- for u in postlist[i]['use'].keys():
+ for plist in postlist:
+ if 'use' in plist:
+ for u in plist['use'].keys():
if u not in isusedby:
isusedby[u] = []
- isusedby[u].append(postlist[i]['name'])
- for i in range(len(postlist)):
- if postlist[i]['block'] == 'python module' and '__user__' in postlist[i]['name']:
- if postlist[i]['name'] in isusedby:
+ isusedby[u].append(plist['name'])
+ for plist in postlist:
+ if plist['block'] == 'python module' and '__user__' in plist['name']:
+ if plist['name'] in isusedby:
# if not quiet:
- outmess('Skipping Makefile build for module "%s" which is used by %s\n' % (
- postlist[i]['name'], ','.join(['"%s"' % s for s in isusedby[postlist[i]['name']]])))
+ outmess(
+ f'Skipping Makefile build for module "{plist["name"]}" '
+ 'which is used by {}\n'.format(
+ ','.join(f'"{s}"' for s in isusedby[plist['name']])))
if 'signsfile' in options:
if options['verbose'] > 1:
outmess(
@@ -448,8 +451,8 @@ def run_main(comline_list):
outmess('%s %s\n' %
(os.path.basename(sys.argv[0]), options['signsfile']))
return
- for i in range(len(postlist)):
- if postlist[i]['block'] != 'python module':
+ for plist in postlist:
+ if plist['block'] != 'python module':
if 'python module' not in options:
errmess(
'Tip: If your original code is Fortran source then you must use -m option.\n')
diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py
index 8d1b6e5be..2a4402c89 100644
--- a/numpy/lib/index_tricks.py
+++ b/numpy/lib/index_tricks.py
@@ -149,9 +149,9 @@ class nd_grid:
try:
size = []
typ = int
- for k in range(len(key)):
- step = key[k].step
- start = key[k].start
+ for kk in key:
+ step = kk.step
+ start = kk.start
if start is None:
start = 0
if step is None:
@@ -161,19 +161,19 @@ class nd_grid:
typ = float
else:
size.append(
- int(math.ceil((key[k].stop - start)/(step*1.0))))
+ int(math.ceil((kk.stop - start) / (step * 1.0))))
if (isinstance(step, (_nx.floating, float)) or
isinstance(start, (_nx.floating, float)) or
- isinstance(key[k].stop, (_nx.floating, float))):
+ isinstance(kk.stop, (_nx.floating, float))):
typ = float
if self.sparse:
nn = [_nx.arange(_x, dtype=_t)
for _x, _t in zip(size, (typ,)*len(size))]
else:
nn = _nx.indices(size, typ)
- for k in range(len(size)):
- step = key[k].step
- start = key[k].start
+ for k, kk in enumerate(key):
+ step = kk.step
+ start = kk.start
if start is None:
start = 0
if step is None:
@@ -181,7 +181,7 @@ class nd_grid:
if isinstance(step, (_nx.complexfloating, complex)):
step = int(abs(step))
if step != 1:
- step = (key[k].stop - start)/float(step-1)
+ step = (kk.stop - start) / float(step - 1)
nn[k] = (nn[k]*step+start)
if self.sparse:
slobj = [_nx.newaxis]*len(size)
diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py
index 23021cafa..c40e50a57 100644
--- a/numpy/lib/polynomial.py
+++ b/numpy/lib/polynomial.py
@@ -152,9 +152,8 @@ def poly(seq_of_zeros):
return 1.0
dt = seq_of_zeros.dtype
a = ones((1,), dtype=dt)
- for k in range(len(seq_of_zeros)):
- a = NX.convolve(a, array([1, -seq_of_zeros[k]], dtype=dt),
- mode='full')
+ for zero in seq_of_zeros:
+ a = NX.convolve(a, array([1, -zero], dtype=dt), mode='full')
if issubclass(a.dtype.type, NX.complexfloating):
# if complex roots are all complex conjugates, the roots are real.
@@ -770,8 +769,8 @@ def polyval(p, x):
else:
x = NX.asanyarray(x)
y = NX.zeros_like(x)
- for i in range(len(p)):
- y = y * x + p[i]
+ for pv in p:
+ y = y * x + pv
return y
@@ -1273,14 +1272,14 @@ class poly1d:
s = s[:-5]
return s
- for k in range(len(coeffs)):
- if not iscomplex(coeffs[k]):
- coefstr = fmt_float(real(coeffs[k]))
- elif real(coeffs[k]) == 0:
- coefstr = '%sj' % fmt_float(imag(coeffs[k]))
+ for k, coeff in enumerate(coeffs):
+ if not iscomplex(coeff):
+ coefstr = fmt_float(real(coeff))
+ elif real(coeff) == 0:
+ coefstr = '%sj' % fmt_float(imag(coeff))
else:
- coefstr = '(%s + %sj)' % (fmt_float(real(coeffs[k])),
- fmt_float(imag(coeffs[k])))
+ coefstr = '(%s + %sj)' % (fmt_float(real(coeff)),
+ fmt_float(imag(coeff)))
power = (N-k)
if power == 0:
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 1d694e92f..829691b1c 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -2772,11 +2772,6 @@ class TestInterp:
assert_almost_equal(np.interp(x, xp, fp, period=360), y)
-def compare_results(res, desired):
- for i in range(len(desired)):
- assert_array_equal(res[i], desired[i])
-
-
class TestPercentile:
def test_basic(self):
diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py
index fb7ba7874..a148e53da 100644
--- a/numpy/lib/tests/test_shape_base.py
+++ b/numpy/lib/tests/test_shape_base.py
@@ -392,7 +392,7 @@ class TestArraySplit:
assert_(a.dtype.type is res[-1].dtype.type)
# Same thing for manual splits:
- res = array_split(a, [0, 1, 2], axis=0)
+ res = array_split(a, [0, 1], axis=0)
tgt = [np.zeros((0, 10)), np.array([np.arange(10)]),
np.array([np.arange(10)])]
compare_results(res, tgt)
@@ -713,5 +713,9 @@ class TestMayShareMemory:
# Utility
def compare_results(res, desired):
- for i in range(len(desired)):
- assert_array_equal(res[i], desired[i])
+ """Compare lists of arrays."""
+ if len(res) != len(desired):
+ raise ValueError("Iterables have different lengths")
+ # See also PEP 618 for Python 3.10
+ for x, y in zip(res, desired):
+ assert_array_equal(x, y)
diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py
index b1a916d4a..1f2cb66fa 100644
--- a/numpy/lib/utils.py
+++ b/numpy/lib/utils.py
@@ -351,8 +351,7 @@ def who(vardict=None):
maxshape = 0
maxbyte = 0
totalbytes = 0
- for k in range(len(sta)):
- val = sta[k]
+ for val in sta:
if maxname < len(val[0]):
maxname = len(val[0])
if maxshape < len(val[1]):
@@ -369,8 +368,7 @@ def who(vardict=None):
prval = "Name %s Shape %s Bytes %s Type" % (sp1*' ', sp2*' ', sp3*' ')
print(prval + "\n" + "="*(len(prval)+5) + "\n")
- for k in range(len(sta)):
- val = sta[k]
+ for val in sta:
print("%s %s %s %s %s %s %s" % (val[0], ' '*(sp1-len(val[0])+4),
val[1], ' '*(sp2-len(val[1])+5),
val[2], ' '*(sp3-len(val[2])+5),