在不更改原始lis中某些值的情况下创建预置换列表

2024-06-17 08:36:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个非图形程序,但在理解以下内容时遇到了问题: 我正在尝试使用以下参数的递归创建嵌套列表:

  • row:由1、0或-1组成的列表,例如[0,-1,-1,1]

  • lst:将作为单个选项构建的空lst

  • i:运行递归的索引

  • *final:将构建的列表的最终列表

原始列表中的1和0必须保持不变,-1必须更改为0或1。 我必须返回一个列表列表,其中包含可以从原始列表中组合的所有选项 以下是一些例子-

 input: `[-1,1,1,-1,1]`
output: `[[1, 1, 1, 1, 1], [1, 1, 1, 0, 1], [0, 1, 1, 1, 1], [0, 1, 1, 0, 1]]`

input:`[-1,-1,-1]`
output:`[[1, 1, 1], [1, 1, 0], [1, 0, 1], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 0, 1], [0, 0, 0]]`

input:`[0,-1,-1]`
output: `[[0, 1, 1], [0, 1, 0], [0, 0, 1], [0, 0, 0]]`

此代码适用于[-1,-1,-1]这样的情况,但不适用于第一个expsample这样的输入。它从原始列表中更改了0和1,但不应更改

 BLACK = 1
 WHITE = 0
 UNKNOWN = -1


    def row_helper(row, lst, i, final):
    if len(lst) == len(row):
        copied = copy.deepcopy(lst)
        final.append(copied)
        return
    if row[i] == BLACK or row[i] == WHITE:
        lst.append(row[i])
        row_helper(row, lst, i + 1, final)
    else:
        lst.append(BLACK)
        row_helper(row,  lst, i + 1, final)
        lst.pop()
        lst.append(WHITE)
        row_helper(row,  lst, i + 1, final)
        lst.pop()

final1 = []
j = 0
lst2 = []
row1 = [1, 0, -1, -1]
row_helper(row1,lst2, j, final1)

我试着用元组替换列表编辑,然后再转换成一个列表,这段代码确实适用于每种情况,但我试图找出如何在不使用元组的情况下修复第一段代码 这是一个有效的方法:

def row_helper(row, temp_tup, i, valid_options):
    if i == len(row):
        painted_row = [block for block in temp_tup]
        valid_options.append(painted_row)
        return
    if row[i] == BLACK or row[i] == WHITE:
        temp_tup = temp_tup + (row[i],)
        row_helper(row,  temp_tup, i + 1, valid_options)
    else:
        temp_tup = temp_tup + (BLACK,)
        row_helper(row,  temp_tup, i + 1, valid_options)
        temp_tup = temp_tup[:-1]
        temp_tup = temp_tup + (WHITE,)
        row_helper(row,  temp_tup, i + 1, valid_options)


final1 = []
j = 0
lst2 = tuple()
row1 = [0,-1,-1]
row_helper(row1, lst2, j, final1)
print(final1)

我将非常感激你的帮助


Tags: helper列表iftempfinalrowoptionsblack