此函式的目標是水平翻轉類似矩陣的字串。
例如字串:'100010001' 有 2 行和 3 列看起來像:
1 0 0
0 1 0
0 0 1
但翻轉時應如下所示:
0 0 1
0 1 0
1 0 0
因此該函式將回傳以下輸出:'001010100'
需要注意的是,我不能使用串列或陣列。只有字串。
我相信我寫的當前代碼應該可以作業,但是它回傳一個空字串。
def flip_horizontal(image, rows, column):
horizontal_image = ''
for i in range(rows):
#This should slice the image string, and map image(the last element in the
#coloumn : to the first element of the column) onto horizontal_image.
#this will repeat for the given amount of rows
horizontal_image = horizontal_image image[(i 1)*column-1:i*column]
return horizontal_image
這再次回傳一個空字串。任何線索是什么問題?
uj5u.com熱心網友回復:
用于[::-1]反轉影像的每一行。
def flip(im, w):
return ''.join(im[i:i w][::-1] for i in range(0, len(im), w))
>>> im = '100010001'
>>> flip(im, 3)
'001010100'
uj5u.com熱心網友回復:
range 函式可用于將您的字串隔離為表示行的步驟。在遍歷字串時,您可以使用[::-1]反轉每一行以實作水平翻轉。
string = '100010001'
output = ''
prev = 0
# Iterate through string in steps of 3
for i in range(3, len(string) 1, 3):
# Isolate and reverse row of string
row = string[prev:i]
row = row[::-1]
output = output row
prev = i
輸入:
'100
010
001'
輸出:
'001
010
100'
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426022.html
