我熟悉比較 2 個整數和字符串列表;然而,當比較包含額外字符的 2 個字符串列表時,可能會有點挑戰。假設輸出包含以下內容,我將其分解為字符串列表。我在我的代碼中稱它為 diff。輸出164c164< Apples = ---> Apples = 0168c168< Berries = ---> Berries = false218c218< Cherries = ---> Cherries = 20223c223< Bananas = ---> Bananas = 10233,234c233,234< Lemons = 2< Strawberries = 4---> Lemons = 4> Strawberries = 2264c264< Watermelons = ---> Watermelons = 524288第二組字符串包含我希望與第一個列表進行比較的忽略變量。>>> ignore['Apples', 'Lemons']我的代碼:>>> def str_compare (ignore, output):... flag = 0... diff = output.strip ().split ('\n')... if ignore:... for line in diff:... for i in ignore:... if i in line:... flag = 1... if flag:... flag = 0... else:... print (line)... >>>該代碼適用于 Apple 和 Lemons 省略。>>> str_compare(ignore, output)164c164---168c168< Berries = ---> Berries = false218c218< Cherries = ---> Cherries = 20223c223< Bananas = ---> Bananas = 10233,234c233,234< Strawberries = 4---> Strawberries = 2264c264< Watermelons = ---> Watermelons = 524288>>>必須有更好的方法來比較 2 個不是 O(n^2) 的字符串。如果我的差異列表不包含像“Apples =”這樣的額外字符,那么可以使用 O(n) 來比較兩個列表。在不遍歷每個差異元素上的“忽略”變量的情況下進行比較的任何建議或想法?
添加回答
舉報
0/150
提交
取消