我正在嘗試創建一個遞回,它將遍歷具有許多雙值的大串列,并將創建一個具有唯一值的串列。我可以通過一個簡單的 for 回圈來做到這一點,但我試圖通過遞回來解決它。
我設法創建了一個具有唯一值的字串,但我似乎無法理解如何創建一個串列。
當然我可以將我的字串加入一個串列,但我正在嘗試在函式中創建串列。
thread_sold_split 是我的雙值大串列。顏色是我試圖通過遞回創建的串列。
def distinct_colors(color_list):
if not color_list:
return color_list
if not color_list[1:]:
return color_list[0]
dis_color = distinct_colors(color_list[1:])
if color_list[0] in dis_color:
return dis_color
return color_list[0] ' ' dis_color
print(colors := distinct_colors(thread_sold_split))
另外,有人告訴我我可以洗掉第二個“if”塊,因為我已經在第三個“if”塊中檢查了串列的頭部(第一個值),但是當我將它注釋掉時它停止作業并回傳錯誤。

uj5u.com熱心網友回復:
代碼
def distinct_colors(color_list, seen = None):
'''
Returns unique items of color_list
'''
if seen is None:
seen = set() # keeps track of items we have seen
if not color_list: # Base case (empty list)
return color_list
# Split color list into first element and rest
first, *rest = color_list
if first in seen:
return distinct_colors(rest, seen) # already seen first element
else:
seen.add(first) # update items we have seen
return [first] distinct_colors(rest, seen) # Add first element to recurse on rest of elements
測驗
測驗 1
print(distinct_colors(['r', 'r', 'b', 'g', 'g', 'g']))
Out: ['r', 'b', 'g']
測驗 2
thread_sold_split = ['white', 'white', 'blue', 'white', 'blue', 'white',
'white', 'yellow', 'purple', 'purple', 'yellow', 'purple',
'yellow', 'blue', 'blue', 'purple', 'blue', 'white', 'white',
'red', 'white', 'blue', 'red', 'blue', 'green', 'blue', 'green',
'blue', 'red', 'green']
print(distinct_colors(thread_sold_split))
Out: ['white', 'blue', 'yellow', 'purple', 'red', 'green']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527072.html
上一篇:回圈中串列的長度
