我有两个固定大小的字符串列表,我想检查这两个列表是否与以下示例“相似”:
list1 = ["a", None, "c", None, "e", None]
list2 = ["a", "b", "c", "d", "e", "f"]
similar = True
for i in xrange(6):
if list1[i] is not None:
if list1[i] != list2[i]:
similar = False
break
有没有更快的方法呢?
更新:我刚刚使用zip
测试了一些解决方案。它们并不快,因为zip
会考虑两个列表中的所有元素。请注意,在许多情况下,两个列表中的第一个元素是不同的,因此我提供的程序会立即停止检查剩余元素,从而提供更快的解决方案。
答案 0 :(得分:0)
如果你担心提前退出,你可以这样做:
iter1, iter2 = iter(list1), iter(list2)
similar = True
while True: # or `while similar`
try:
a, b = next(iter1), next(iter2)
except StopIteration:
break
if a is not None and b is not None and a != b:
similar = False
break
# similar is your result
与...相同:
import itertools
all(a==b for a,b in itertools.izip(list1, list2) if a is not None and b is not None)
与...相同:
import itertools
for a,b in itertools.izip(list1, list2):
if a is None or b is None:
continue
if a != b:
break
else:
# similar
答案 1 :(得分:0)
有没有更快的方法呢?
是的,摆脱嵌套的if
会产生一些小的差异:
list1 = ["a", None, "c", None, "e", None]
list2 = ["a", "b", "c", "d", "e", "f"]
similar = True
for i in xrange(6):
if list1[i] is not None and list1[i] != list2[i]:
similar = False
break
print(similar)
# True
我认为这个算法错了。如果list1
和list2
互换:
list1, list2 = list2, list1
similar = True
for i in xrange(6):
if list1[i] is not None and list1[i] != list2[i]:
similar = False
break
print(similar)
# False
但它们是相同的两个列表,应该仍然被认为是相似的。 IMO此代码检查两个列表中的None
是正确的:
similar = True
for i in xrange(6):
if ((list1[i] is not None and list2[i] is not None) and
list1[i] != list2[i]):
similar = False
break
print(similar)
# True