【发布时间】:2018-01-01 19:12:22
【问题描述】:
我写了一个函数来根据以下条件检查字符串:
- 检查字符串中的任何单词是否在列表 1 中。
- 如果字符串在列表 1 中,则返回位置以查看它旁边的项目是否在 该字符串在列表 2 中。
- 如果在列表 1 和列表 2 中,则返回 True。
- 否则返回 False。
棘手的部分是这些列表真的很长。因此,为了提高效率,列表 2 中的第一次出现将返回 True 并移动到下一个字符串。
以下是我扼杀的代码,但我怀疑它是否按预期工作。效率也是她的关键。我尝试创建列表 1 和列表 2 的完整组合,然后循环遍历,但每个字符串循环超过 1 亿次似乎有点疯狂。
第一个代码:
def double_loop(words):
all_words = words.split()
indices = [n for n,x in enumerate(allwords) if x in list1]
if len(indices) != 0:
for pos in indices[:-1]:
if all_words[pos+1] in list2:
return True
#the purpose here is not to continue looking #through the whole list of indices, but end as soon as list2 contains an item 1 position after.
break
else:
return False
我不确定上面的代码是否根据我上面的逻辑工作。比较起来;
第二个代码:
def double_loop(words):
all_words = words.split()
indices = [n for n,x in enumerate(allwords) if x in list1]
if len(indices) != 0:
indices2 = [i for i in indices[:-1] if all_words[i+1] in list2]
if len(indices2) != 0:
return True
else:
return False
else:
return False
根据我的测试数据具有相同的运行时间。
我想更清楚的问题是,我的第一个代码是否会真正运行,直到找到符合其标准的“第一个”元素并中断。还是它仍然像第二个代码一样贯穿所有元素。
【问题讨论】:
-
“我怀疑它是否按预期工作”
-
嗨,对不起,我应该更准确,运行时间很慢,我不知道这是否是适合我的目的的正确代码。
-
这不能回答@timgeb 的问题。代码怎么没有按照你想要的方式工作?
-
换句话说,你遇到了什么错误。
-
并且您提供的代码无法运行:
allwordsvsall_words。