[英]Using recursion, count the number of identical elements in the list and collect this in a dictionary
請幫助實現以下功能:
給定一個字符串和列表的列表,其中也可能包含字符串和列表等。您的工作是將這些字符串收集到一個字典中,其中 key 是字符串,value 是這些列表中該字符串出現的次數。
def count_strings(data: list, pos=None, result: dict = None) -> dict:
"""
:param data: given list of lists
:param pos: figure out how to use it
:param result: figure out how to use it
:return: dict of given symbols and their count
"""
我的嘗試:
if result is None and pos is None:
result = {}
pos = 0
if pos > len(data):
return result
if isinstance(data[pos], str):
return count_strings(data, pos + 1, result)
elif isinstance(data, list):
return count_strings(data, 0, result)
輸出應該是這樣的:
print(count_strings([[], ["J", "*", "W", "f"], ["j", "g", "*"], ["j", "8", "5", "6", "*"], ["*", "*", "A", "8"]]))
# {'J': 1, '*': 5, 'W': 1, 'f': 1, 'j': 2, 'g': 1, '8': 2, '5': 1, '6': 1, 'A': 1}
print(count_strings([[], [], [], [], ["h", "h", "m"], [], ["m", "m", "M", "m"]])) # {'h': 2, 'm': 4, 'M': 1}
print(count_strings([])) # {}
print(count_strings([['a'], 'b', ['a', ['b']]])) # {'a': 2, 'b': 2}
您獲得的模板並沒有促進最佳實踐(請參閱改變參數的 Python 函數的正確樣式),但忽略這一點,您的代碼存在以下問題:
if pos > len(data)
:這會錯過這兩個相等的情況,在這種情況下,您還應該輸入if
塊data[pos]
是一個列表,而不是data
。data[pos]
這是一個更正:
def count_strings(data: list, pos=None, result: dict = None) -> dict:
if result is None and pos is None:
result = {}
pos = 0
if pos < len(data): # pos should not be equal to len when accessing data[pos]:
if isinstance(data[pos], str):
result[data[pos]] = result.get(data[pos], 0) + 1 # increment count
elif isinstance(data[pos], list):
count_strings(data[pos], 0, result) # process nested list
count_strings(data, pos + 1, result) # process the remaining entries
return result
如果函數不需要將要變異的result
參數,也不需要pos
參數,那就更好了。 雖然您不是在尋找改變您獲得的模板的解決方案,但我仍然更喜歡在此處包含替代方案。
這里實際上有兩個問題需要解決:
這兩者可以在單獨的函數中解決。 在不使用庫的情況下,您可以按如下方式執行此操作:
def deepvalues(data):
if isinstance(data, list):
for item in data:
yield from deepvalues(item) # recursion
else:
yield data
def count_strings(data: list) -> dict:
result = {}
for value in deepvalues(data):
result[value] = result.get(value, 0) + 1
return result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.