【发布时间】:2014-07-01 03:46:23
【问题描述】:
我想我有一个无限循环?我制作了一本字典,其中搜索词作为键和一个索引,这些键在 my_string 中找到。我想创建一个 search_dict,其中列出了 my_string 中所有匹配项的列表,作为每个键的索引作为搜索词。
我的 search_dict 没有被填充,除了一个包含数百万个项目的项目。
my_string='Shall I compare thee to a summer\'s day?'
#string_dict has only a single index as a value where its key was found in my_string
string_dict={'a': 36, ' ': 34, 'e': 30, '': 39, 'h': 17, 'm': 29, 'l': 4, 'o': 22, 'e ': 19, 's': 33, 'r': 31, 't': 21, ' t': 20, 'e t': 19}
#I'd like search_dict to have all indices for key matches in my_string
search_dict=dict()
for key in string_dict:
search_dict[key]=list()
for item in search_dict:
start=0
end=len(my_string)
found=my_string.find(item,start,end)
while start<end:
if found>=0:
search_dict[key].append(found)
start=found+len(item)
found=my_string.find(item,start,end)
else:
break
print search_dict
我也尝试了以下更改。仍然不确定为什么如果 my_string.find 出现 -1(未找到),则循环不会为下一次搜索键迭代而中断。
else:
break
#with
if found<0:
break
【问题讨论】:
-
寻找代码审查?
-
我正在学习这样做,复习可能会有所帮助。我不明白为什么它会永远循环。
-
是的,你有一个无限循环。查看第二个
while语句中的条件。 -
我尝试替换第二个 while 语句,但仍然卡住...hrmph
-
哎呀!抱歉,我实际上误读了代码——我忘记了
find在失败时返回-1。现在我看到了你真正的问题。对于您字典中的一项,len(item)将为零!所以start不会前进,然后当find再次运行时,它会再次找到相同的项目;它的len仍然为零,start不会前进……但我会让你在字典中查找哪个项目。
标签: python string list search dictionary