我有一个递归建立的函数(该函数在具有嵌套分区的表的SQL查询中查找所需的组成部分)。如果有2个分区级别(在这种情况下,是年和月),则该表如下所示:
[[['theyear', '>=', 2014], ['OR'], ['theyear', '==', 2014, 'AND', [['themonth', '>=', 8], ['OR'], ['themonth', '==', 8, 'AND', False]]]], [['theyear', '<=', 2015], ['OR'], ['theyear', '==', 2015, 'AND', [['themonth', '<=', 9], ['OR'], ['themonth', '==', 9, 'AND', False]]]]]
我想做的就是简化
['themonth', '>=', 8], ['OR'], ['themonth', '==', 8, 'AND', False]
得到公正:
['themonth', '==', 8]
但是嵌套列表可以具有任何深度(例如,表可以按“ theyear”,“ themonth”,“ theday”,“ thehour”进行分区)。我知道示例中的depth = 2,但是我正在努力找出如何自动更改mylist [0] [-1] [-1]的值并更改mylist [0] [-1]如果深度= 4,则为[-1] [-1] [-1]。
一个简单的说法是,如果我有
a = [3, [4, [5]]]
而且我知道深度是3,我不能仅仅使用while循环来做
b = a[-1]
b = b[-1]
b = [6]
>>> a
[3, [4, [5]]]
如何定义一个函数来更改最右边的值?
最佳答案
def changeLast(nested, new):
last = nested[-1]
if isinstance(last, list):
changeLast(last, new)
else:
nested[-1] = new
a = [3, [4, [5]]]
changeLast(a, 6)
print(a)
[3, [4, [6]]]
我没有进行任何错误检查。特别是,我不知道您将如何处理空白清单。
关于python - 如何有效地更改未知深度列表中最右边的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32982594/