首页 > 解决方案 > 将列表列表中的多个值与另一个列表列表匹配并返回值的 Pythonic 方法

问题描述

我正在尝试将列表列表中的两个或多个值与另一个列表列表匹配,并从其中一个列表中返回一个值。很像 SQL 的 on 子句——在 x.field = y.field 和 x.field = y.field 上。

画出您亚马逊账户中的交易清单。id 是唯一的,但名称会发生​​变化(该死的亚马逊!)。我想根据最大日期使用姓氏/头衔。我可能可以使用初始数据集执行以下操作,但想不出怎么做。我正在将行作为列表列表读取。

我只是在做一个通过亚马逊购买进行梳理的个人项目,但可以看到这在未来非常有用。我有一个解决方案,但我认为它会运行很长时间,具体取决于数据的大小。我见过人们将 Pandas 的数据框称为解决方案,但我正在尝试首先学习 Python 的标准库。这是我在 Stack 上的第一个问题,我很抱歉并提前感谢您。

#Example data set comes from a csv I've read into different list of lists
#Fields in order are ID, date (max date from csv to id) -- data set is unique row count 140
X = [['b12', 8/1/2019], ['c34', 7/25/2018],..]
#Fields in order are ID, date, Name -- data set is unique, due to date, row count 1,231
Y = [['b12', 6/23/19, 'item 1'], ['b12', 7/21/19, 'item 1.0'], ['b12', 8/1/19, 'item 1.1'],..]

#Code that works, but I'm sure is 'expensive'
for i in X:
    for n in Y:
        if i[0] == n[0] and i[1] == n[1]:
           i.append(x[2])
        else: continue


#Result is either I append to X (like I have) or create a new list of lists all together
X
[['b12', 8/1/2019, 'item 1.1'], ['c34', 7/25/2019, 'item 2.8'],...]

标签: pythonpython-3.6

解决方案


Y您可以使用(id, date)as 键和nameas 值从列表中创建映射字典。然后使用列表推导从列表中创建一个新列表,X其中包含映射字典中的映射值

>>> X = [['b12', '8/1/2019'], ['c34', '7/25/2018']]
>>> Y = [['b12', '6/23/19', 'item 1'], ['b12', '7/21/19', 'item 1.0'], ['b12', '8/1/19', 'item 1.1'], ['c34', '7/25/18', 'item2.1']]
>>> 
>>> mapping = {(id, date):name for id,date,name in Y}
>>> res = [[id, date, mapping[(id, date.replace('/20', '/'))]] for id,date in X]
>>> 
>>> print (res)
[['b12', '8/1/2019', 'item 1.1'], ['c34', '7/25/2018', 'item2.1']]

推荐阅读