将前三个元素用作键合并多个列表
给定一个列表 o,其包含多个内部列表,每个内部列表具有四个元素:cmd、opt、xx.x(x)se 和 catxxxx。目标是将 o 中前三个元素(cmd、opt 和 xx.x(x)se)用作键,并将具有相同键的列表的第四个元素合并为一个列表。
Python 3.14.3
微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。
下载
以下
python
代码提供了一种方法来实现此目标:
def combine_list(list1, list2):
list0 = list1[:]
if list1[0] == list2[0] and list1[1] == list2[1] and list1[2] == list2[2]:
list_temp = [list1[3], list2[3]]
list0[3] = list_temp
return list0
else:
pass
o = []
a = ['cmd', ['opt1', 'opt2'], '12.2(2)SE', 'Cat3560']
b = ['cmd', ['opt1', 'opt2'], '12.2(2)SE', 'Cat4500']
c = ['cmd', ['opt1', 'opt2', 'opt3', 'opt4'], '12.3(2)SE', 'Cat3560']
d = ['cmd', ['opt1', 'opt2', 'opt3'], '12.4(2)SE', 'Cat3560']
o.append(a)
o.append(b)
o.append(c)
o.append(d)
o_new = o[:]
i = 1
j = 0
for i in range(i, len(o)):
temp = combine_list(o[j], o[i])
if temp is not None:
o_new.append(temp)
o_new.remove(o[j])
o_new.remove(o[i])
if i == 3:
j += 1
i = 1
if j == 3:
break
print(o_new)