Nếu bạn chỉ có một tham chiếu đến một chuỗi và bạn kết hợp một chuỗi khác vào cuối, thì CPython hiện các trường hợp đặc biệt này và cố gắng mở rộng chuỗi tại chỗ.
Kết quả cuối cùng là hoạt động được khấu hao o [n].
e.g.
s = ""
for i in range[n]:
s+=str[i]
Đã từng là o [n^2], nhưng bây giờ nó là o [n].
Từ nguồn [byteObject.c]:
void
PyBytes_ConcatAndDel[register PyObject **pv, register PyObject *w]
{
PyBytes_Concat[pv, w];
Py_XDECREF[w];
}
/* The following function breaks the notion that strings are immutable:
it changes the size of a string. We get away with this only if there
is only one module referencing the object. You can also think of it
as creating a new string object and destroying the old one, only
more efficiently. In any case, don't use this if the string may
already be known to some other part of the code...
Note that if there's not enough memory to resize the string, the original
string object at *pv is deallocated, *pv is set to NULL, an "out of
memory" exception is set, and -1 is returned. Else [on success] 0 is
returned, and the value in *pv may or may not be the same as on input.
As always, an extra byte is allocated for a trailing \0 byte [newsize
does *not* include that], and a trailing \0 byte is stored.
*/
int
_PyBytes_Resize[PyObject **pv, Py_ssize_t newsize]
{
register PyObject *v;
register PyBytesObject *sv;
v = *pv;
if [!PyBytes_Check[v] || Py_REFCNT[v] != 1 || newsize < 0] {
*pv = 0;
Py_DECREF[v];
PyErr_BadInternalCall[];
return -1;
}
/* XXX UNREF/NEWREF interface should be more symmetrical */
_Py_DEC_REFTOTAL;
_Py_ForgetReference[v];
*pv = [PyObject *]
PyObject_REALLOC[[char *]v, PyBytesObject_SIZE + newsize];
if [*pv == NULL] {
PyObject_Del[v];
PyErr_NoMemory[];
return -1;
}
_Py_NewReference[*pv];
sv = [PyBytesObject *] *pv;
Py_SIZE[sv] = newsize;
sv->ob_sval[newsize] = '\0';
sv->ob_shash = -1; /* invalidate cached hash value */
return 0;
}
Nó đủ dễ dàng để xác minh theo kinh nghiệm.
$ python -m timeit -s"s=''" "for i in xrange[10]:s+='a'" 1000000 loops, best of 3: 1.85 usec per loop $ python -m timeit -s"s=''" "for i in xrange[100]:s+='a'" 10000 loops, best of 3: 16.8 usec per loop $ python -m timeit -s"s=''" "for i in xrange[1000]:s+='a'" 10000 loops, best of 3: 158 usec per loop $ python -m timeit -s"s=''" "for i in xrange[10000]:s+='a'" 1000 loops, best of 3: 1.71 msec per loop $ python -m timeit -s"s=''" "for i in xrange[100000]:s+='a'" 10 loops, best of 3: 14.6 msec per loop $ python -m timeit -s"s=''" "for i in xrange[1000000]:s+='a'" 10 loops, best of 3: 173 msec per loop
Tuy nhiên, điều quan trọng cần lưu ý là tối ưu hóa này không phải là một phần của thông số Python. Nó chỉ trong việc triển khai Cpython theo như tôi biết. Ví dụ, cùng một thử nghiệm thực nghiệm trên Pypy hoặc Jython có thể hiển thị hiệu suất O [N ** 2] cũ hơn. however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O[n**2] performance .
$ pypy -m timeit -s"s=''" "for i in xrange[10]:s+='a'" 10000 loops, best of 3: 90.8 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange[100]:s+='a'" 1000 loops, best of 3: 896 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange[1000]:s+='a'" 100 loops, best of 3: 9.03 msec per loop $ pypy -m timeit -s"s=''" "for i in xrange[10000]:s+='a'" 10 loops, best of 3: 89.5 msec per loop
Cho đến nay rất tốt, nhưng sau đó,
$ pypy -m timeit -s"s=''" "for i in xrange[100000]:s+='a'" 10 loops, best of 3: 12.8 sec per loop
ouch thậm chí còn tồi tệ hơn bậc hai. Vì vậy, Pypy đang làm một cái gì đó hoạt động tốt với các chuỗi ngắn, nhưng hoạt động kém cho các chuỗi lớn hơn.
Sử dụng phương thức toán tử hoặc tham gia để nối một ký tự vào Chuỗi Python.+ operator or join method to append a character into string Python. Mã ví dụ đơn giản nối chuỗi vào chuỗi khác trong Python. Chuỗi Python là một đối tượng bất biến, vì vậy bất kỳ phương thức nào thực hiện một số hành động trên chuỗi trả về một chuỗi mới. Sử dụng toán tử + Nó kết hợp hai chuỗi hoặc một chuỗi và một ký tự và trả về một chuỗi mới trong Python. Output::
s = "Hell"
c = "o"
print[s + c]
Sử dụng phương thức Jop []
Phương thức chuỗi.join [] kết hợp tất cả các phần tử đối tượng có thể sử dụng chuỗi làm dấu phân cách giữa các phần tử.
s = "Hell"
c = "o"
res = "".join[[s, c]]
print[res]
Đầu ra: Xin chào: Hello
Hãy bình luận nếu bạn có bất kỳ nghi ngờ và đề xuất nào không có chủ đề char Python này.
Lưu ý: IDE: & NBSP; Pycharm & NBSP; 2021.3.3 [Phiên bản cộng đồng] IDE: PyCharm 2021.3.3 [Community Edition]
Windows 10
Python 3.10.1
Tất cả & nbsp; ví dụ python & nbsp; là trong & nbsp; Python & nbsp; 3, vì vậy có thể khác với các phiên bản Python 2 hoặc nâng cấp. Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Bằng cấp về Khoa học máy tính và Kỹ sư: Nhà phát triển ứng dụng và có nhiều ngôn ngữ lập trình kinh nghiệm. Sự nhiệt tình cho công nghệ và thích học kỹ thuật.