我熟悉比较 2 个整数和字符串列表;然而,当比较包含额外字符的 2 个字符串列表时,可能会有点挑战。
假设输出包含以下内容,我将其分解为字符串列表。我在我的代码中称它为 diff。
输出
164c164
< Apples =
---
> Apples = 0
168c168
< Berries =
---
> Berries = false
218c218
< Cherries =
---
> Cherries = 20
223c223
< Bananas =
---
> Bananas = 10
233,234c233,234
< Lemons = 2
< Strawberries = 4
---
> Lemons = 4
> Strawberries = 2
264c264
< 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 = false
218c218
< Cherries =
---
> Cherries = 20
223c223
< Bananas =
---
> Bananas = 10
233,234c233,234
< Strawberries = 4
---
> Strawberries = 2
264c264
< Watermelons =
---
> Watermelons = 524288
>>>
必须有更好的方法来比较 2 个不是 O(n^2) 的字符串。如果我的差异列表不包含像“Apples =”这样的额外字符,那么可以使用 O(n) 来比较两个列表。在不遍历每个差异元素上的“忽略”变量的情况下进行比较的任何建议或想法?
相关分类