我正在学习Python.我遇到了性能问题.对于单个字典,我想删除密钥if
如果,我不想删除密钥
我的密钥是唯一的字符串,大多数长度在3-50个字符之间.我正在使用的词典有100,000个或更多的项目,进行了数十亿次比较.由于这是一个O(n ^ 2)问题,我应该停止尝试优化此代码吗?还是有空间在这里取得进展?
字典是可取的,但我对其他类型开放.
例如:'hello'包含'he'和'ell'.我想在保持'你好'的同时删除'he'和'ell'键.我想在其他键的中间删除前缀,后缀和键子串.
密钥一个接一个地生成并添加到字典中.然后reduce_dict(dictionary)运行.我的假设是:在将它们添加到字典中时进行的测试与后面的函数测试一样慢,如下面的代码所示.
def reduce_dict(dictionary):
reduced = dictionary.copy()
for key in dictionary:
for key2 in dictionary:
if key != key2:
if key2 in key:
reduced.pop(key2, 0)
return reduced
Run Code Online (Sandbox Code Playgroud) 我希望有条件地连接列表的更有效方法的建议.
这种技术似乎有效:
sentence = ['this ','is ','are ','a ','sentence']
string = ''
for i in sentence:
if i != 'are ':
string += i
Run Code Online (Sandbox Code Playgroud) python string list string-concatenation conditional-statements
我有这个代码块我想评论,但内联注释不起作用.我不确定PEP8指南适用于何处.建议吗?
if next_qi < qi + lcs_len \ # If the next qLCS overlaps
and next_ri < ri + lcs_len \ # If the next rLCS start overlaps
and next_ri + lcs_len > ri: # If the next rLCS end overlaps
del candidate_lcs[qi] # Delete dupilicate LCS.
Run Code Online (Sandbox Code Playgroud) python ×3
comments ×1
continuation ×1
dictionary ×1
list ×1
pep8 ×1
performance ×1
python-2.7 ×1
string ×1