[英]Handling the various permutations of the diff between two lists
給定兩個列表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,請說; 否則,對於每個列表,說它為空或列出其內容。
嘗試這個:
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.