【发布时间】:2022-01-08 01:03:16
【问题描述】:
我在列表中有一个表达式:
l = [['h'], '+', ['c'], '-', ['d'], '+', [['e'], '-', ['f'], '+', ['y']], '+', ['a']]
我想通过创建大小为 3 的列表来构建二进制格式的表达式,直到整个原始列表都被迭代。这意味着如果存在任何嵌套的列表列表,我也必须遍历它们。 结果是这样的:
final_list = [[[[['h'], '+', ['c']], '-', ['d']], '+', [[['e'], '-', ['f']], '+', ['y']]], '+', ['a']]
我试过了:
count = 0
def make_list(l):
final_list = []
temp_list = []
for index, value in enumerate(l):
count += 1
if len(value) == 1 or (value == '+' or value == '-'):
temp_list.append(value)
elif len(value) != 1:
final_list.append(make_list(l[index]))
if count == 3:
final_list.append(temp_list[:])
temp_list.clear()
count = 1
return final_list
这段代码的问题是它从 temp_list 中添加了新的列表,所以得到的答案是这样的:
[[[[['h'], '+', ['c']], ['-', ['d']], '+', [[['e'], '-', ['f']], '+', ['y']], '+', ['a']]]
编辑: MYousefi 的解决方案适用于任何表达式,只要它不是大小为 3。但是当输入像这样大小为 3 的表达式时:
[['b'], '+', [['c'], '-', ['d'], '+', ['e']]]
然后他的解决方案不会在嵌套列表中连续访问和创建大小为 3 的列表。
【问题讨论】:
-
快速提示:将
final_list = []移动到函数定义内部