假设我想在Python 2.7中获取字符串的特定字符,假设
a = 'abcdefg...' # a long string
print a[5]
想知道什么时候访问字符串的任何特定字符,例如,访问第5个元素,想知道性能是什么,是恒定时间O(1),还是线性性能O(n)要么根据5(位置)我们正在访问的字符),或整个字符串的线性性能O(n)(本例中为len(a))?
的问候, 林
答案 0 :(得分:4)
>>> long_string_1M ="".join(random.choice(string.printable) for _ in xrange(1000000))
>>> short_string = "hello"
>>> timeit.timeit(lambda:long_string_1M[50000])
0.1487280547441503
>>> timeit.timeit(lambda:short_string[4])
0.1368805315209798
>>> timeit.timeit(lambda:short_string[random.randint(0,4)])
1.7327393072888242
>>> timeit.timeit(lambda:long_string_1M[random.randint(50000,100000)])
1.779330312345877
看起来像O(1)给我
他们实现了它,因为一个字符串是连续的内存位置,所以索引到它只是一个偏移的问题......如果你知道c / c ++类似{{1}那么就没有寻求(至少这是我的理解) (自从我做了C以来已经很长时间了,所以可能有点不对劲)
答案 1 :(得分:4)
除了Joran的回答,我还会指出this reference implementation,确认他的回答是O(1)查询
/* String slice a[i:j] consists of characters a[i] ... a[j-1] */
static PyObject *
string_slice(register PyStringObject *a, register Py_ssize_t i,
register Py_ssize_t j)
/* j -- may be negative! */
{
if (i < 0)
i = 0;
if (j < 0)
j = 0; /* Avoid signed/unsigned bug in next line */
if (j > Py_SIZE(a))
j = Py_SIZE(a);
if (i == 0 && j == Py_SIZE(a) && PyString_CheckExact(a)) {
/* It's the same as a */
Py_INCREF(a);
return (PyObject *)a;
}
if (j < i)
j = i;
return PyString_FromStringAndSize(a->ob_sval + i, j-i);
}
为什么这应该是你的直觉
Python strings are immutable。这种常见的优化允许在需要时假设连续数据的技巧。请注意,在引擎盖下,我们有时只需要计算C中内存位置的偏移量(显然是特定于实现的)
There are several places字符串的不变性是可以依赖(或烦恼)的东西。在python作者的话中;
字符串是不可变的有几个优点。一个是 性能:知道字符串是不可变的意味着我们可以分配 创造时的空间
因此,尽管我们可能无法保证,但据我所知,这种行为在各种实现中都是非常安全的。