小编123*_*213的帖子

如果它是任何其他键中的子字符串,请删除字典键

我正在学习Python.我遇到了性能问题.对于单个字典,我想删除密钥if

  • a键是另一个键中的子字符串

如果,我不想删除密钥

  • 关键子串本身就是

我的密钥是唯一的字符串,大多数长度在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)

python performance dictionary

5
推荐指数
1
解决办法
1339
查看次数

有条件地将字符串列表与条件连接起来

我希望有条件地连接列表的更有效方法的建议.

这种技术似乎有效:

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

3
推荐指数
2
解决办法
3101
查看次数

评论续行

我有这个代码块我想评论,但内联注释不起作用.我不确定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 comments pep8 python-2.7 continuation

0
推荐指数
1
解决办法
533
查看次数