[英]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.