如何使用 Python 代码将具有相同前三个元素的多个列表合并为一个新的列表?
知识点掌握了,还需要不断练习才能熟练运用。下面给大家带来一个文章开发实战,手把手教大家学习《如何使用 Python 代码将具有相同前三个元素的多个列表合并为一个新的列表?》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!
将前三个元素用作键合并多个列表
给定一个列表 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 代码将具有相同前三个元素的多个列表合并为一个新的列表?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注公众号,带你了解更多关于的知识点!