私信  •  关注

Riccardo Bucco

Riccardo Bucco 最近创建的主题
Riccardo Bucco 最近回复了
3 年前
回复了 Riccardo Bucco 创建的主题 » 为什么比较python中匹配的字符串比不匹配的字符串更快?

不是 总是 比较匹配字符串的速度更快。相反,比较共享相同id的字符串总是更快。身份确实是这种行为的原因(正如@S3DEV精辟地解释的那样)的一个证明是:

>>> x = 'toto'
>>> y = 'toto'
>>> z = 'totoo'[:-1]
>>> w = 'abcd'
>>> x == y
True
>>> x == z
True
>>> x == w
False
>>> id(x) == id(y)
True
>>> id(x) == id(z)
False
>>> id(x) == id(w)
False
>>> timeit.timeit('x==y', number=100000000, globals={'x': x, 'y': y})
3.893762200000083
>>> timeit.timeit('x==z', number=100000000, globals={'x': x, 'z': z})
4.205321462000029
>>> timeit.timeit('x==w', number=100000000, globals={'x': x, 'w': w})
4.15288594499998

比较具有相同id的对象总是更快(正如您从示例中注意到的,比较 x z 相比于 十、 y ,那是因为 十、 Z 不要共享相同的id)。

这是一个可能的解决方案:

def split_txt(txt, sep, n):
    if any(len(s) + 1 > n for s in txt.split(sep)):
        raise Exception('The text cannot be split')
    result = []
    start = 0
    while start + n <= len(txt):
        result.append(txt[start:start + n].rsplit(sep, 1)[0] + sep)
        start += len(result[-1])
    if start < len(txt):
        result.append(txt[start:])
    return result
        
5 年前
回复了 Riccardo Bucco 创建的主题 » 将Python字典中的JSON值累积为数组

import pandas as pd

result = [{"source": source, "neighbors": df["target"].tolist()}
          for source, df in pd.DataFrame(data["links"]).groupby("source")]