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

Python 如何有效地更改未知深度列表中最右边的值?,python,python-2.7,Python,Python 2.7,我有一个递归构建的函数(该函数在具有嵌套分区的表的SQL查询中查找所需的组件部分)。如果有两个分区级别(在本例中为年和月),则该表如下所示: 要获得公正: ['themonth', '==', 8] 但是嵌套列表可以有任何深度(例如,表可以按“theyear”、“themonth”、“theday”、“thehour”进行分区)。我知道示例中的depth=2,但我正在努力找出如何自动更改mylist[0][1][1]的值。。。如果深度为4,则更改mylist[0][1][1][1] 更简单的说

我有一个递归构建的函数(该函数在具有嵌套分区的表的SQL查询中查找所需的组件部分)。如果有两个分区级别(在本例中为年和月),则该表如下所示:

要获得公正:

['themonth', '==', 8]
但是嵌套列表可以有任何深度(例如,表可以按“theyear”、“themonth”、“theday”、“thehour”进行分区)。我知道示例中的depth=2,但我正在努力找出如何自动更改mylist[0][1][1]的值。。。如果深度为4,则更改mylist[0][1][1][1]

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

a = [3, [4, [5]]]
我知道深度是3,我不能用while循环来做

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

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

您要么需要一个循环,要么递归执行。然后,对于每个级别,检查项目是否是带有
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

我没有做任何错误检查。特别是,我不知道您希望如何处理空列表。

我应该添加一个警告:您需要确保您的输入不包含自引用<代码>l=[];l、 附加(l);获取最右侧(l)永远不会终止,因为深度是无限的。在您的情况下,这可能不会发生,但如果有人在未经检查的用户输入上使用此选项:您已收到警告:-)
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
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]]]