gpt4 book ai didi

将列表列表中的多个值与另一个列表列表匹配并返回值的 Pythonic 方法

转载 作者:行者123 更新时间:2023-12-01 07:25:59 25 4
gpt4 key购买 nike

我正在尝试将一个列表列表中的两个或多个值与另一个列表列表进行匹配,并从其中一个列表返回一个值。很像 SQL 的 on 子句 - 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'],...]

最佳答案

您可以从列表 Y 创建一个映射字典,其中 (id, date) 作为键,name 作为值。然后使用列表理解从列表 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']]

关于将列表列表中的多个值与另一个列表列表匹配并返回值的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57451783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com