如何有效地更改未知深度列表中最右边的值?

时间:2015-10-07 02:01:28

标签: python python-2.7

我有一个我递归构建的函数(该函数在具有嵌套分区的表的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]

但是嵌套列表可以是任何深度(例如,表格可以通过&#39;他们早期&#39;,&#39; themonth&#39;,&#39; theday&#39;,& #39; thehour&#39)。我知道示例中的深度= 2,但我正在努力弄清楚如何自动更改mylist [0] [ - 1] [ - 1]的值......并更改mylist [0] [ - 1] [ - 1] [ - 1] [ - 1]如果深度= 4。

更简单的说法是,如果我有

a = [3, [4, [5]]]

我知道深度是3,我不能只使用while循环来实现

b = a[-1]
b = b[-1]
b = [6]
>>> a
[3, [4, [5]]]

如何定义一个函数来改变最右边的值?

2 个答案:

答案 0 :(得分:1)

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]]]

我还没有完成任何错误检查。特别是,我不知道你想如何处理一个空列表。

答案 1 :(得分:0)

您需要循环或递归执行。然后为每个级别检查项目是否为isinstance()的列表。如果没有找到最深的清单。

这是一种迭代方法:

def get_rightmost(l):
  while True:
    try:
      # get last item of current list
      item = l[-1]
    except IndexError:
      # empty list, return it
      return l
    # check if item is a list
    if isinstance(item, list):
      # continue with the list in the last item
      l = item
    else:
      # return the current list
      return l

要更改最右边的值,请设置返回列表的最后一个元素:

 rightmost_list = get_rightmost(your_list)
 rightmost_list[-1] = new_value # might fail with IndexError if list is empty.
 # So add a try-except block if you can't be sure the lists are never empty