
将前三个元素用作键合并多个列表
给定一个列表 o,其包含多个内部列表,每个内部列表具有四个元素:cmd、opt、xx.x(x)se 和 catxxxx。目标是将 o 中前三个元素(cmd、opt 和 xx.x(x)se)用作键,并将具有相同键的列表的第四个元素合并为一个列表。
以下 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)以上就是如何使用 Python 代码将具有相同前三个元素的多个列表合并为一个新的列表?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号