合并两个列表列表-Python [英] Merge two lists of lists - Python

查看:97
本文介绍了合并两个列表列表-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一本很棒的入门书,但没有回答我需要的内容: 在Python中组合两个排序的列表

This is a great primer but doesn't answer what I need: Combining two sorted lists in Python

我有两个Python列表,每个列表都是日期时间,值对的列表:

I have two Python lists, each is a list of datetime,value pairs:

list_a = [['1241000884000', 3], ['1241004212000', 4], ['1241006473000', 11]]

并且:

list_x = [['1241000884000', 16], ['1241000992000', 16], ['1241001121000', 17], ['1241001545000', 19], ['1241004212000', 20], ['1241006473000', 22]]

  1. 实际上有许多具有不同键/值的list_a列表.
  2. 所有list_a日期时间都在list_x中.
  3. 我要创建一个列表list_c,它与每个list_a相对应,每个list_a的日期时间分别来自list_x和value_a/value_x.

奖金:

在我的实际程序中,list_a实际上是像这样的字典中的列表.以字典级别的答案将是:

In my real program, list_a is actually a list within a dictionary like so. Taking the answer to the dictionary level would be:

dict = {object_a: [['1241000884000', 3], ['1241004212000', 4], ['1241006473000', 11]], object_b: [['1241004212000', 2]]}

虽然我可以弄清楚那部分.

I can figure that part out though.

推荐答案

以下代码可以满足您的要求.您可以将对列表直接转换为字典.然后,可以通过将密钥集相交来找到共享的密钥.最后,只要有一组共享密钥,构建结果字典就很容易.

Here's some code that does what you asked for. You can turn your list of pairs into a dictionary straightforwardly. Then keys that are shared can be found by intersecting the sets of keys. Finally, constructing the result dictionary is easy given the set of shared keys.

dict_a = dict(list_a)
dict_x = dict(list_x)

shared_keys = set(dict_a).intersection(set(dict_x))

result = dict((k, (dict_a[k], dict_x[k])) for k in shared_keys)

这篇关于合并两个列表列表-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆