如何回傳我希望更改的串列中值的地址?
我可以通過這種方式更改串列中的值:
a = [1, 2, 3]
a[0] = 0
但是如何更改輔助函式選擇的值?
helper = lambda x: x[0]
a = [1, 2, 3]
helper(a) = 0
將產生運行時錯誤型別語法錯誤(因為python將其解釋為1 = 0)
我的問題是如何構建一個為我選擇索引的函式?
僅回傳索引的函式沒有幫助:
例子:
helper = lambda x: 0
a = [1, 2, 3]
a[helper(a)] = 0
不會解決(例如)二維串列的問題:
helper_1 = lambda x: 0, 0
a = [[1, 2, 3]]
a[helper(a)[0]][helper(a)[1]] = 0
正如你所看到的,這使得代碼非常難看,非常快。
我將針對這個問題提供兩個簡單的例子:
第一個示例代碼,一維串列:
lst = [1, 2, 3]
for x in lst:
x *= 2
# will not change the list
如果有指標:
for &x in lst:
*x *= 2
第二個示例代碼,二維串列:
def rotate_90(image, direction):
rows, columns = len(image), len(image[0])
rotated = empty_2d(columns, rows) # allocate 2d list
rotated_place = lambda row, col: rotated[col][-1- row] \
if direction =='R' else \
lambda row, col: rotated[-1-col][row]
for row in range(rows):
for col in range(columns):
rotated_place(row, col) = image[row][col] # error
return rotated
# will produce an error
如果有指標:
def rotate_90(image, direction):
rows, columns = len(image), len(image[0])
rotated = empty_2d(columns, rows) # aloccate memory
rotated_place = lambda row, col: &rotated[col][-1- row] \
if direction =='R' else \
lambda row, col: &rotated[-1-col][row]
for row in range(rows):
for col in range(columns):
*rotated_place(row, col) = image[row][col]
return rotated
uj5u.com熱心網友回復:
為了清楚起見,您希望將其列印出來[42, 2, 3]:
first = ...
a = [1, 2, 3]
first(a) = 42
print(a)
您可以使用它first[a]代替first(a):
class First:
def __setitem__(_, lst, value):
lst[0] = value
first = First()
a = [1, 2, 3]
first[a] = 42
print(a)
在線試試吧!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360384.html
