合并 python 中的两个元组列表

merging two lists of tuples in python

假设这些是我的列表:

oracle_files = [
    (1, "__init__.py"),
    (2, "price_calc.py"),
    (3, "lang.py")]
predicted_files = [
    (5, ["random.py","price_calc.py"]),
    (2, ["__init__.py","price_calc.py"]),
    (1, ["lang.py","__init__.py"])]

第一个列表是一个元组列表,其中每个元组都有一个标识符和一个字符串。 第二个是整数元组列表和字符串列表

我的意图是创建第三个列表,通过 ID(整数)将这两个列表相交

输出应如下所示:

result = [(2, "price_calc.py", ["__init__.py","price_calc.py"]), 
          (1, "__init__.py", ["lang.py","__init__.py"])]

你知道达到这个输出的方法吗?因为我没弄对。

我想这就是你想要的。

oracle_files = [(1, "__init__.py"), (2, "price_calc.py"), (3, "lang.py")]
predicted_files = [(5, ["random.py","price_calc.py"]), (2, ["__init__.py","price_calc.py"]), (1, ["lang.py","__init__.py"])]

dct = dict(oracle_files)
for k,v in predicted_files:
    if k in dct:
        dct[k] = (dct[k], v)
print(dct)

outlist = [(k,)+v for k,v in dct.items() if isinstance(v,tuple)]
print(outlist)

输出:

{1: ('__init__.py', ['lang.py', '__init__.py']), 2: ('price_calc.py', ['__init__.py', 'price_calc.py']), 3: 'lang.py'}
[(1, '__init__.py', ['lang.py', '__init__.py']), (2, 'price_calc.py', ['__init__.py', 'price_calc.py'])]

这是一个使用字典的方法:

oracle_files = [(1, "__init__.py"), (2, "price_calc.py"), (3, "lang.py")]
predicted_files = [(5, ["random.py","price_calc.py"]), (2, ["__init__.py","price_calc.py"]), (1, ["lang.py","__init__.py"])]

dct1 = dict(oracle_files)
dct2 = dict(predicted_files)

result = [(k, dct1[k], dct2[k]) for k in dct1.keys() & dct2.keys()]
print(result) # [(1, '__init__.py', ['lang.py', '__init__.py']), (2, 'price_calc.py', ['__init__.py', 'price_calc.py'])]

这使用了一个方便的事实,即从 dict.keys() 获得的字典键的行为就像一个集合。

Keys views are set-like since their entries are unique and hashable. [...] For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects