我有一个如下矩阵:
`
matrix =
[
['P', 'o', 'P', 'o', 'P'],
['m', 'i', 'c', 's', 'r'],
['g', 'a', 'T', 'A', 'C'],
['n', 'n', 'e', 'r', 't'],
['a', 'g', 'o', 'd', 'o'],
['a', 'p', 'p', 'l', 'e']
]`
此代码以重复的“对角向右”方式打印每个字母:
`test_word = ''
for upper in range(len(matrix)):
for rep1 in range(min(upper + 1, len(matrix[0]))):
for rep2 in range(rep1, min(upper + 1, len(matrix[0]))):
for j in range(rep1, rep2 + 1):
test_word += (matrix[upper - j][j])
print(test_word)
test_word = ''`
输出:
`
P,m,m,mo,o,g,g,gi
......when it arrives to the diagonal anTsP here is the output:
a,a,an,a,an,anT,a,an,anT,anTs,a,an,anT,anTs,anTsP`
问题是它重复一次重复一次,一次和一次... 如果您不了解该模式,那么我想遍历每个对角线并尝试找到“拼写”字母的方法,例如,我对anTsP对角线的理想输出为:
a, an, anT, anTs, anTsP, n,nT,nTs,nTsP, T, etc.
如果您有任何想法,
答案 0 :(得分:0)
看来print
语句中的缩进错误:
test_word = ''
for upper in range(len(matrix)):
for rep1 in range(min(upper + 1, len(matrix[0]))):
for rep2 in range(rep1, min(upper + 1, len(matrix[0]))):
for j in range(rep1, rep2 + 1):
test_word += (matrix[upper - j][j])
print(test_word, end=' ') # <--- indent left
test_word = ''
但是这仅打印:
P m mo o g gi giP i iP P n na nac naco a ac aco c co o a an anT anTs anTsP n nT nTs nTsP T Ts TsP s sP P a ag age ageA ageAr g ge geA geAr e eA eAr A Ar r
不是'porC, 'pdt', 'lo', 'e'
对角线。
此示例打印所有对角线:
matrix = [
['P', 'o', 'P', 'o', 'P'],
['m', 'i', 'c', 's', 'r'],
['g', 'a', 'T', 'A', 'C'],
['n', 'n', 'e', 'r', 't'],
['a', 'g', 'o', 'd', 'o'],
['a', 'p', 'p', 'l', 'e']
]
def rotate(l, n):
return l[n:] + l[:n]
def get_substrings(s):
for j in range(0, len(s)):
for i in range(j+1, len(s)+1):
yield s[j:i]
def get_values(matrix):
transposed = [*zip(*matrix)]
for i in range(len(matrix[0])):
transposed[i] = rotate(transposed[i], -i)
transposed = [*zip(*transposed)]
for i, lst in enumerate(transposed, 1):
yield from get_substrings(''.join(lst[:i]))
for i, lst in enumerate(transposed, 1):
yield from get_substrings(''.join(lst[i:]))
for v in get_values(matrix):
print(v, end=' ')
打印:
P m mo o g gi giP i iP P n na nac naco a ac aco c co o a an anT anTs anTsP n nT nTs nTsP T Ts TsP s sP P a ag age ageA ageAr g ge geA geAr e eA eAr A Ar r p po por porC o or orC r rC C p pd pdt d dt t l lo o e
编辑:不包含yield
的版本:
matrix = [
['P', 'o', 'P', 'o', 'P'],
['m', 'i', 'c', 's', 'r'],
['g', 'a', 'T', 'A', 'C'],
['n', 'n', 'e', 'r', 't'],
['a', 'g', 'o', 'd', 'o'],
['a', 'p', 'p', 'l', 'e']
]
def rotate(l, n):
return l[n:] + l[:n]
def get_substrings(s):
rv = []
for j in range(0, len(s)):
for i in range(j+1, len(s)+1):
rv.append(s[j:i])
return rv
def get_values(matrix):
rv = []
transposed = [*zip(*matrix)]
for i in range(len(matrix[0])):
transposed[i] = rotate(transposed[i], -i)
transposed = [*zip(*transposed)]
for i, lst in enumerate(transposed, 1):
rv.extend(get_substrings(''.join(lst[:i])))
for i, lst in enumerate(transposed, 1):
rv.extend(get_substrings(''.join(lst[i:])))
return rv
for v in get_values(matrix):
print(v, end=' ')