這是一個嵌套串列:
matrix = [['0', '0', '0', '0', '0', '1', '1', '0', '0', '0'],
['0', '1', '1', '1', '1', '1', '0', '0', '0', '0'],
['0', '0', '1', '1', '0', '1', '0', '1', '1', '0'],
['0', '1', '0', '0', '0', '0', '1', '0', '0', '1'],
['0', '0', '0', '1', '0', '0', '1', '0', '1', '0'],
['0', '0', '0', '0', '1', '0', '1', '1', '1', '0'],
['0', '1', '1', '1', '1', '0', '1', '1', '1', '1'],
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']]
#output should be [1,2,2,2,3,1,5,3,4,2]
Height = 8
Width = 10
我想知道如何獲得每列的高度。然后每個高度,我想把它放在一個串列中。
我們計算 1,如果它們是伴隨的 1,它們只計算高度。
我們從下面開始計數,然后向上計數。
輸出應該是 [1,2,2,2,3,1,5,3,4,1]
我只想在 Python 函式中使用 build。
我嘗試使用 for 回圈和 if, else 陳述句。
For loop iterate through the list.
like if i == '1' add 1 to counter.
if i == '0' reset counter and add the last value from counter to counter1, but only if counter is greater then counter1.
uj5u.com熱心網友回復:
您可以itertools.takewhile在反向壓縮矩陣上使用:
from itertools import takewhile
out = [len(list(takewhile(lambda x: x=='1', reversed(l)))) for l in zip(*matrix)]
輸出:
[1, 2, 2, 2, 3, 1, 5, 3, 4, 2]
如果您不想 import takewhile,請使用配方:
def takewhile(predicate, iterable):
# takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
for x in iterable:
if predicate(x):
yield x
else:
break
這個怎么運作:
zip 旋轉矩陣:
>>> list(zip(*matrix))
[('0', '0', '0', '0', '0', '0', '0', '1'),
('0', '1', '0', '1', '0', '0', '1', '1'),
('0', '1', '1', '0', '0', '0', '1', '1'),
('0', '1', '1', '0', '1', '0', '1', '1'),
('0', '1', '0', '0', '0', '1', '1', '1'),
('1', '1', '1', '0', '0', '0', '0', '1'),
('1', '0', '0', '1', '1', '1', '1', '1'),
('0', '0', '1', '0', '0', '1', '1', '1'),
('0', '0', '1', '0', '1', '1', '1', '1'),
('0', '0', '0', '1', '0', '0', '1', '1')]
串列理解以reversed相反的方式旋轉(實際上將每一行反轉):
>>> [list(reversed(l)) for l in zip(*matrix)]
[['1', '0', '0', '0', '0', '0', '0', '0'],
['1', '1', '0', '0', '1', '0', '1', '0'],
['1', '1', '0', '0', '0', '1', '1', '0'],
['1', '1', '0', '1', '0', '1', '1', '0'],
['1', '1', '1', '0', '0', '0', '1', '0'],
['1', '0', '0', '0', '0', '1', '1', '1'],
['1', '1', '1', '1', '1', '0', '0', '1'],
['1', '1', '1', '0', '0', '1', '0', '0'],
['1', '1', '1', '1', '0', '1', '0', '0'],
['1', '1', '0', '0', '1', '0', '0', '0']]
takewhile在條件為 True 時保留元素,此處為'1'( lambda x: x=='1') 時保留元素,并len獲取輸出的長度:
>>> l = ['1', '1', '1', '0', '0', '0', '1', '0']
>>> list(takewhile(lambda x: x=='1', l))
['1', '1', '1']
>>> len(list(takewhile(lambda x: x=='1', l)))
3
注意。zip, reversed,takewhile等函式是生成器,除非有東西消耗它,否則它們不會產生輸出,這就是我list(generator(…))在示例中使用的原因
使用經典 python 回圈的解決方案:
out = []
for l in zip(*matrix):
counter = 0
for elem in reversed(l):
if elem == '1':
counter =1
else:
break
out.append(counter)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374267.html
上一篇:當步長大于1時,通過陣列切片和numpy.diff替換python中的for回圈
下一篇:將多列與具有多個值的串列進行比較
