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

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

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

问题:

如何将列表 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:        passo = []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 = 0for 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:            breakprint(o_new)

以上就是如何将列表中相同前三列的数据合并到第四列?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1350478.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 15:06:49
下一篇 2025年12月11日 07:42:14

相关推荐

发表回复

登录后才能评论
关注微信