
合并多个列表,以其中前三列为键
问题:
如何将列表 o 中的每一行前三列(cmd、opt 和 xx.x(x)se)作为键,合并第四列(catxxxx)的元素?
回答:
可以使用以下函数 combine_list() 将两个行合并:
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 的所有行,并将它们与其他所有行进行比较:
o_new = o[:]
for i in range(1, 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最后,打印合并后的列表 o_new:
print(o_new)
最终代码:
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[:]
j = 0
for i in range(1, 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)以上就是如何将列表中相同前三列的数据合并到第四列?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号