【问题标题】:Most performant / efficient way to action new and old items comparing two lists?比较两个列表的最高效/最有效的操作新旧项目的方法?
【发布时间】:2020-08-06 14:43:00
【问题描述】:

我的用例是我有一个事物列表(比如原始记录)和一个更新事物列表(更新的记录)。对于更新列表中的任何全新事物,我想执行一个操作(比如发送通知电子邮件)。对于原始列表中不再在更新列表中的任何内容,我想执行不同的操作(比如记录旧/过时的记录)。对于原始列表中的任何事物,也仍然在更新列表中,不需要任何操作。平等是由价值决定的。

详细:

for updated_record in updated_records:
   if updated_record not it original_records:
      send_notification_email_for(updated_record)

for original_record in original_records:
   if original_record not in updated_records:
      log_outdated(original_record)

我觉得我的生产代码可读性很强:

removed_records = set(original_records).difference(updated_records)
new_records = set(updated_records).difference(original_records)
log_outdated(removed_records)
send_notification_email_for(new_records)

请注意,log_outdatedsend_nofitication_email 函数还需要再次遍历过滤后的 removed_records 和 new_records 集合。

每个列表(原始和更新)可能有数千条记录,所以如果有人对相同逻辑的更有效版本有任何建议,我很感兴趣?

【问题讨论】:

  • 既然你有工作代码,而且你问的是效率,这个问题似乎更适合CodeReview

标签: python list algorithm collections


【解决方案1】:

你可以使用集合。

In [10]: originals = 'r1 r2 r3 r4'.split()

In [11]: originals
Out[11]: ['r1', 'r2', 'r3', 'r4']

In [12]: updated = 'r3 r4 r5 r6'.split()

In [13]: updated
Out[13]: ['r3', 'r4', 'r5', 'r6']

In [14]: for first_only in set(originals) - set(updated):
    ...:     print(first_only)
r1
r2

In [15]: for second_only in set(updated) - set(originals):
    ...:     print(second_only)
r5
r6

In [16]: for both in set(originals) & set(updated):
    ...:     print(both)
r4
r3

In [17]: 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2011-01-19
    相关资源
    最近更新 更多