查找数组是否包含有一个不匹配的字符串
我想说列表中有一个字符串只有一个不匹配
def check(list, s):
n = len(list)
# If the array is empty
if (n == 0):
return False
for i in range(0, n, 1):
# If sizes are same
if (len(list[i]) != len(s)):
continue
diff = False
for j in range(0, len(list[i]), 1):
if (list[i][j] != s[j]):
# If first mismatch
if (diff == False):
diff = True
# Second mismatch
else:
diff = False
break
if (diff):
return True
return False
这段代码没问题,但运行速度很慢。如何使用字典使其更快?
I want say there is a string in the list with only one mismatch
def check(list, s):
n = len(list)
# If the array is empty
if (n == 0):
return False
for i in range(0, n, 1):
# If sizes are same
if (len(list[i]) != len(s)):
continue
diff = False
for j in range(0, len(list[i]), 1):
if (list[i][j] != s[j]):
# If first mismatch
if (diff == False):
diff = True
# Second mismatch
else:
diff = False
break
if (diff):
return True
return False
This code is okay but it works slowly. How can I make it faster using a dictionary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 zip() 将两个字符串的每个字符配对,并使用 sum() 来计算不匹配的数量。 any() 函数将允许您检查列表中每个项目的匹配:
这将转换为以下基本 for 循环:
[编辑] 为了使其运行得更快一点,字符串比较可以使用 zip() 作为一个迭代器,以便比较不需要转到每个字符串的末尾:
You can use zip() to pair up each character of two strings and sum() to count the number of mismatches. The any() function will allow you to check for a match over every item in the list:
This translates to the following basic for-loop:
[EDIT] to make this go a bit faster, the string comparisons can use zip() as an iterator so that the comparison doesn't need to go to the end of every string: