我想使用嵌套列表的列表.然后通过使用递归打印列表中索引0或2的最大值和索引0或2的最小值.
I want to take in a list with nested lists. Then print the highest value of index 0 or 2 in the list and the lowest value of index 0 or 2, through using recursion.
这是我到目前为止得到的:
This is what I got so far:
lst = [1, 5, [7, 10, []]] def high_low(my_list): new_lst = [] if not my_list: print max(new_lst) print min(new_lst) elif isinstance(my_list[0], int): return new_lst.append(my_list[0]) + high_low(my_list[2:]) elif isinstance(my_list[0], list): return new_lst.append(max(my_list[0])) + high_low(my_list[2:])这是我遇到的问题,因为我不知道如何从嵌套列表中获取最高和最低值,然后将其附加到新的空列表中.例如,这就是我希望输出看起来像的样子:
This is where I get stuck, as I don't know how to get the highest and lowest value from a nested list and then append it to the new empty list. For example this is what I want the output to look like:
>>> print_tree(lst) 10 1 推荐答案这可以使用类似的&经典的问题解决方法(将不规则的列表弄平),无需重新发明轮,只需使用一些工作方法和后处理:
this can be achieved using a similar & classic problem solving (Flatten an irregular list of lists), no need to reinvent the wheel, just use some working method & post-process:
展平列表列表,然后取 min &最多.
Flatten the list of lists, then take min & max of it.
import collections def flatten(l): # function copied from the link above for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)): yield from flatten(el) else: yield el lst = [1, 5, [7, 10, []]] new_list = list(flatten(lst)) # create a list cos we'll be iterating twice on it print(max(new_list)) print(min(new_list))结果
10 1通过手动循环进行一次迭代:
with one iteration with a manual loop:
min_value = None max_value = None for v in flatten(lst): if min_value is None or v < min_value: min_value = v if max_value is None or v > max_value: max_value = v print(min_value) print(max_value)flatten 方法很不错,因为它不会创建临时的 list 元素,因此不会产生不必要的内存分配.
the flatten method is nice because it doesn't create temporary list elements so no unneccesary memory allocations.
更多推荐
使用递归的嵌套列表的最高和最低值
发布评论