我正在编写一些以一种奇怪的方式循环通过两个列表的代码。我的目标是a
使用index遍历整个list i
,然后b
使用index循环j
并来回交替。即我想按顺序遍历配对:
(0,0),...,(n,0),(0,1)...(0,m),(1,1)...,(n,1),(1,2)...,(1,m),(2,2),...,(n,m)
我当前的代码是这样写的:
while i+j < len(a) + len(b) -2:
#do stuff
if direction_toggle:
if i + 1 > len(a):
direction_toggle = not direction_toggle
i = j
else:
i += 1
else:
if j + 1 > len(b):
direction_toggle = not direction_toggle
j = i + 1
else:
j += 1
但是,我想变得更pythonic,并遵循
扁平比嵌套更好。
我要写的东西看起来像这样:
while i+j < len(a) + len(b) -2:
#do stuff
if direction_toggle:
var, length = i, len(a)
else:
var, length = j, len(b)
if var + 1 > length:
direction_toggle = not direction_toggle
else:
var += 1
所以我的问题是:是否有一种方法可以实现相同的目标,但要减少重复性并去除嵌套层?广义上讲,我的代码非常简单,但是似乎没有办法避免以两种不同的方式重复自己,我是否错过了某些东西,或者我的实现实际上是实现这一目标的最有效方法?
PS:我希望这不是重复的,我找不到解决此主题的任何其他问题。
编辑度:我的具体要求是,我处理(i, j-1)
,(i-1, j)
并(i-1, j-1)
打之前(i, j)
。满足此要求的任何可能的迭代路径都将起作用。如果您有兴趣,这是因为我正在尝试实现DTW算法,其中矩阵中分配的每个值都取决于先前的相邻值。
如果将数字排列在按n列的m列网格中,则可以通过在第一列中向下移动,然后跨过第一行(从第一列开始),然后在第二列向下(从行开始)来获得解决方案1),然后跨第二行(从第2列开始),然后跨到第三列(从第2行开始),依此类推。这只是实现了这一点。
def gen_tuples(n_rows, n_cols):
row = col = 0
while row <= n_rows and col <= n_cols:
for i in range(row, n_rows + 1):
yield (i, col)
for j in range(col + 1, n_cols + 1):
yield (row, j)
row += 1
col += 1
list(gen_tuples(5, 3))
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0),
(0, 1), (0, 2), (0, 3),
(1, 1), (2, 1), (3, 1), (4, 1), (5, 1),
(1, 2), (1, 3),
(2, 2), (3, 2), (4, 2), (5, 2),
(2, 3),
(3, 3), (4, 3), (5, 3)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句