两个以上列表合并到一个列表,python可变参数函数

多个列表,个数不定,比方说
la=[['张三',60],['李四',66],['王五',62]]
lb=[['张三',70],['李四',76]]
lc=[['张三',90],,['王五',92]]
合并后
lst==[['张三',60,70,90],['李四',66,76,None],['王五',62,None,92]]
python可变参数函数如何写?
谢谢

阅读 2.4k
2 个回答
def foo(*ls):
    mapping = {}
    for i, l in enumerate(ls):
        record = []
        for name, value in l:
            if name not in mapping:
                mapping[name] = list()
            if not mapping[name]:
                mapping[name].extend(None for _ in range(i))

            mapping[name].append(value)
            record.append(name)

        for name in mapping.keys():
            if name not in record:
                mapping[name].append(None)

    return [[key] + value for key, value in mapping.items()]


if __name__ == '__main__':
    print(foo([['张三', 60], ['李四', 66], ['王五', 62]],
              [['张三', 70], ['李四', 76]],
              [['张三', 90], ['王五', 92]],
              [['李四', 10], ['赵六', 20]],
              [['王五', 89], ['李四', 70]]))

非常谢谢!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题