繁体   English   中英

处理两个列表之间的差异的各种排列

[英]Handling the various permutations of the diff between two lists

给定两个列表todays_idsbaseline_ids ,我将使用以下内容来编译它们之间的差异:

    # Status                     added_ids             removed_ids
    # No IDs removed, none added []                    []
    # IDs removed, none added    []                    [id1, id2, ..]
    # IDs added, IDs removed     [id1, id2, ..]        [id1, id2, ..]
    # IDs added, none removed    [id1, id2, ..]        []

    added_ids = [_id for id in todays_ids if _id not in baseline_ids]
    removed_ids = [_id for id in baseline_ids if _id not in todays_ids]

然后,我需要采取不同的操作,具体取决于任何给定执行的四种可能结果中的哪一种。 为简单起见,让我们假设在每种情况下我只需要打印所有相关的ID。

if len(added_ids) == 0 and len(removed_ids) > 0
   print 'No new ids'
   print 'The following ids were removed_ids:'
   for _id in removed_ids:
       print _id 

elif len(added_ids) > 0 and len(removed_ids) > 0
   print 'The following ids were added:'
   for _id in added_ids:
       print _id 
   print 'The following ids were removed:'
   for _id in removed_ids:
       print _id 

elif len(added_ids) > 0 and len(removed_ids) == 0
   print 'The following ids were added:'
   for _id in added_ids:
       print _id 
   print 'No ids removed'

else:
    print 'No ids added or removed'

显然,这里有一些重复的工作(也许是在使用列表理解的差异设置中, 以及在随后的逻辑中),而不必要的是。 如何改善?

如果长度的总和均为0,请说; 否则,对于每个列表,说它为空或列出其内容。

尝试这个:

today_ids = ['id1', 'id2', 'id5']
base_line_ids = ['id1','id2','id3','id4']

added_ids = set(today_ids).difference(base_line_ids)
removed_ids = set(base_line_ids).difference(today_ids)

# specific message for: no added, no removed
if set(today_ids) == set(base_line_ids):
    print('No ids added or removed')
    exit(0)

if len(removed_ids):
    print('The following ids were removed:\n{}'.format('\n'.join(removed_ids)))
else:
    print('No ids removed')

if len(added_ids):
    print('The following ids were added:\n{}'.format('\n'.join(added_ids)))
else:
    print('No ids added')

输出:

The following ids were removed:
id4
id3
The following ids were added:
id5
added_ids = set(today_ids).difference(set(baseline_ids))
removed_ids = set(baseline_ids).difference(set(today_ids))

if added_ids:
    if removed_ids:
        do_something
    else:
        do_something
else:
    if removed_ids:
        do_something
    else:
        do_something

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM