如何将列表中相同前三列的数据合并到第四列?

ID:19873 / 打印

如何将列表中相同前三列的数据合并到第四列?

合并多个列表,以其中前三列为键

问题:

如何将列表 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)
上一篇: Flask 框架中如何使用 `url_for` 生成带有端口号的 URL?
下一篇: Python 中如何利用多线程在 sleep 期间执行其他任务?

作者:admin @ 24资源网   2025-01-14

本站所有软件、源码、文章均有网友提供,如有侵权联系308410122@qq.com

与本文相关文章

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。