鉴于两个列表todays_ids
和baseline_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 :(得分:1)
如果长度的总和都是0,那么这样说;否则对于每个列表,说它是空的或列出其内容。
答案 1 :(得分:1)
试试这个:
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
答案 2 :(得分:1)
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